We have a data.frame like this:
ID 10_1 2_20 [...]
1 1 1 [...]
2 2 1 [...]
We need to change the values of the data frame depending on the name of the column. For example in row 1, the column 10_1 would get the value 1 because 10 is greater than in in "10_1". but column 2_20 in row 1 would get value 0 because 2 is less than 20 in "2_20".
How can I iterate over a data frame and change the value of a column in each row depending on the name of the column?
Thank you
You may try
indx <- (vapply(strsplit(names(df1)[-1], '_'), function(x) {
x1 <- as.numeric(x)
x1[1] >x1[2]}, logical(1L)))+0L
df1[-1] <- indx[col(df1[-1])]
df1
# ID 10_1 2_20
#1 1 1 0
#2 2 1 0
Or you can try sub
v1 <- as.numeric(sub('_.*', '', names(df1)[-1]))
v2 <- as.numeric(sub('.*_', '', names(df1)[-1]))
indx <- (v1 >v2)+0L
df1[-1] <- indx[col(df1[-1])]
df1 <- structure(list(ID = 1:2, `10_1` = 1:2, `2_20` = c(1L, 1L)),
.Names = c("ID","10_1", "2_20"), class = "data.frame",
row.names = c(NA, -2L))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.