I have a data frame
data <- structure(list(GROUP = c("na", "3\nN=0 (0%)", "na", "3\nN=9 (100%)",
"na", "3\nN=9 (100%)"), col6 = c(NA, "NA", NA, "4.5 [2.5; 6.5] \n 4.67 ± 2.5 \n ( 2 - 8 )",
NA, "NA"), col7 = c(NA, "NA", NA, "7.5 [6.25; 9.5] \n 7.83 ± 2.32 \n ( 5 - 11 )",
NA, "NA"), col8 = c(NA, "NA", NA, "9.5 [8.25; 11.5] \n 9.83 ± 2.32 \n ( 7 - 13 )",
NA, "NA"), dif = c(NA, "col6-col7: NA\ncol6-col8: NA\ncol7-col8: 0 [0; 310.5]",
NA, "col1-col2: -3 [-3; -3] \n -1.29 [-2.32; -0.26]\ncol1-col3: -5 [-5; -5] \n -1.74 [-2.84; -0.63]\ncol2-col3: -2 [-2; -2] \n -0.42 [-1.36; 0.51]",
NA, "col8-col6: NA\ncol8-col7: 0 [0; 310.5]\ncol6-col7: NA"),
p.value = c(NA, "col6-col7: NA\ncol6-col8: NA\ncol7-col8: >0.999",
NA, "col1-col2: 0.015*\ncol1-col3: 0.008*\ncol2-col3: 0.020*",
NA, "col8-col6: NA\ncol8-col7: >0.999\ncol6-col7: NA")), row.names = c(NA,
6L), class = "data.frame")
I would like to replace the values in the cells in which the values are "na"
with the values from my name.col list (name.col=c("1","2","3")
)
What was I trying to do
for(i in 1:ncol(data)){
if(data[i,1]=="na"){
data[i, ] <- c(name.col[i], NA,NA, NA,NA,NA)
}
}
CodePudding user response:
Assuming that the name.col
each value should replace each one of the row where 'GROUP' is na
, just replicate the name.col
on the rhs of <-
so that the lengths are same
data[data$GROUP == "na", -1] <- name.col[row(data[data$GROUP == "na", -1])]
Or if it needs to only change the GROUP value
data[data$GROUP == "na", "GROUP"] <- name.col