Gilbert Gilbert - 1 month ago 7
R Question

Replacing values columnwise in R

I have a dataframe that look like the following...

V1 | V2 | V3 | V4
1 | NA | 2 | 5
NA | 2 | NA | NA
1 | 1 | 1 | 1


I would like to transform the dataframe to the following with no header...

V1 | NA | V3 | V4
V2 | NA | NA | NA
V1 | V2 | V3 | V4


In other words, I want the header name in each cell that I have a number columwise.

Data

dd <- read.table(header = TRUE, strip.white = TRUE, sep = '|',
text = "V1 | V2 | V3 | V4
1 | NA | 2 | 5
NA | 2 | NA | NA
1 | 1 | 1 | 1")

Answer

Your expected output seems strange to me but if I understand well, you want to replace every non-NA by the column name?

You can do like this:

df[!is.na(df)] <- rep(names(df), each=nrow(df))[!is.na(df)]

given this data:

df=data.frame(V1=c(1, NA, 1), V2=c(NA, 2, 1), V3=c(2, NA, 1), V4=c(5, NA, 1))

Concerning your wish to get rid of the header, that's impossible in a data.frame. You can transform it into a character matrix and delete the dimnames attributes if you want...

df2 = as.matrix(df); attributes(df2)$dimnames<-NULL
Comments