I have a data frame with three columns:
df <- data.frame(col1=c('71711', '71711', '71711', 'Comment 4', '71711', 'Comment 6'),
col2=c('Comment 1','Comment 2','Comment 3', '24','Comment 5','26'),
col3 = c('21','22','23',NA,'25',NA))
Desired output:
Col1 Col2 Col3
71711 Comment 1 21
71711 Comment 2 22
71711 Comment 3 23
71711 Comment 4 24
71711 Comment 5 25
71711 Comment 6 26
I tried the following but it replaces desired values with numeric one:
for (i in 1:nrow(df))
{
if (any(sapply(df$col2, is.numeric)) == "True" )
df$col3[i] <- df$col2[i]
df$col1[i] <- df$col2[i]
}
Thanks
>Solution :
You can find rows which have NA in col3 and just ‘shift’ values:
indices <- which(is.na(df$col3))
df[indices,] <- append(list(paste0("ID", indices)), df[indices,-3])