gpt4 book ai didi

r - 从数据框中提取带条件的列名

转载 作者:行者123 更新时间:2023-12-03 17:44:01 25 4
gpt4 key购买 nike

dput(new)
structure(list(ID = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
13, 14, 15, 16, 17, 18, 19, 20, 21, 22), A1 = c(1, 1, 1, 1, 0,
0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), A2 = c(1,
1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
), A3 = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0), A4 = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0), A5 = c(0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0), A6 = c(0, 0, 0, 0, 0,
0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), A7 = c(0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0
), A8 = c(0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1,
1, 1, 1, 0, 0), A9 = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0)), row.names = c(NA, -22L), class = c("tbl_df",
"tbl", "data.frame"))

我有以下数据框。我需要提取并打印出现 1 的 id 和逗号分隔的列名。例如:
1 A1,A2
2 A1,A2
3 A1
4 A1
6 A2,A8
7 A6,A8

等等...

如何进行?

这是我的尝试:
vec_ID <- c()
vec_JOB <- c()
job <- 0
for(i in 1 : length(ID)){
for(j in 2:10){
if(new[i,j]==1){
vec_ID[i] <- ID[i]
}
}
}
print(vec_ID)
vec_ID <- vec_ID[!is.na(vec_ID)]
#vec_ID <- as.data.frame(vec_ID)
print(vec_ID)

new_df <- new[ID[vec_ID],]
View(new_df)

for (i in 1:nrow(vec_ID)) {

}

最佳答案

你可以做:

apply(df[-1], 1, function(x) toString(names(df[-1])[as.logical(x)]))

[1] "A1, A2" "A1, A2" "A1" "A1" "" "A2, A8" "A6, A8" "A1, A8" "A6, A8" "A8" "A1, A8" "A6"
[13] "A5, A8" "" "A8" "A8" "A8" "A8" "A8" "A8" "A7" ""

关于r - 从数据框中提取带条件的列名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60668687/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com