[英]transform data frame value based on column name
我們有一個像這樣的data.frame:
ID 10_1 2_20 [...]
1 1 1 [...]
2 2 1 [...]
我們需要根據列名更改數據框的值。 例如,在第1行中,列10_1將獲得值1,因為10大於“ 10_1”中的in。 但第1行的第2_20列將獲得值0,因為“ 2_20”中的2小於20。
如何遍歷數據框並根據列名更改每一行中列的值?
謝謝
你可以試試
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
或者你可以嘗試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))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.