有人能帮我解决这个问题吗。实际上,我有一个有n行m列的数据帧,数据帧的第一列有2个字符串(john,Micheal(,其余列的值为0或1。我试图根据条件if first列命名为name==john,其中一个Multiple列中的值为1,而colname为"1";约翰;否则";其他";
我试过这种方法
names(df) = ifelse(df$name=="John" & rowSums(df[, 2:5800]==1), "John", "Others")
df输入
name col1 col2 col3 col4 col5
john 0 1 0 0 0
Micheal 1 0. 0. 0. 0
john. 0 0. 1. 0 0
期望输出
name others John. john. others. others
john 0 1 0 0 0
Micheal 1 0. 0. 0. 0
john. 0 0. 1. 0 0
感谢
您只能对name
为'john'
的行进行子集设置,并对这些列求和。找出哪一列至少有一个1,并将它们重命名为'John'
,其余的重命名为'Others'
。
inds <- which(colSums(df[df$name == 'john', -1]) > 0) + 1
names(df)[inds] <- 'John'
names(df)[setdiff(2:ncol(df), inds)] <- 'Others'
df
# name Others John John Others Others
#1 john 0 1 0 0 0
#2 Micheal 1 0 0 0 0
#3 john 0 0 1 0 0
但是,请注意,不建议在数据帧中使用相同的列名。您可以使用make.unique
使其独一无二
names(df) <- make.unique(names(df))
数据
df <- structure(list(name = c("john", "Micheal", "john"), col1 = c(0L,
1L, 0L), col2 = c(1, 0, 0), col3 = c(0, 0, 1), col4 = c(0, 0,
0), col5 = c(0L, 0L, 0L)), class = "data.frame", row.names = c(NA,
-3L))