简体   繁体   English

根据列名转换数据框值

[英]transform data frame value based on column name

We have a data.frame like this: 我们有一个像这样的data.frame:

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". 例如,在第1行中,列10_1将获得值1,因为10大于“ 10_1”中的in。 but column 2_20 in row 1 would get value 0 because 2 is less than 20 in "2_20". 但第1行的第2_20列将获得值0,因为“ 2_20”中的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 或者你可以尝试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])]

data 数据

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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM