连接 R 中除最后两列以外的所有列

Concatenate all except last two columns in R

有没有办法连接 R 中除最后两个以外的所有前导列值?

下面是我的数据框的片段

DISEASE Gender  Race    Freq    NEWCOL
Salmonellosis   M   RACE_LATINO_HISPANIC    1   NA
Salmonellosis   F   BLACK_AFRICAN_AMERICAN  2   NA
Salmonellosis   M   WHITE   3   NA
Salmonellosis   M   WHITE   4   NA

使用 concatenate inexcel 获得的期望结果

DISEASE Gender  Race    Freq    NEWCOL  Concat
Salmonellosis   M   RACE_LATINO_HISPANIC    1   NA  Salmonellosis M RACE_LATINO_HISPANIC
Salmonellosis   F   BLACK_AFRICAN_AMERICAN  2   NA  Salmonellosis F BLACK_AFRICAN_AMERICAN
Salmonellosis   M   WHITE   3   NA  Salmonellosis M WHITE
Salmonellosis   M   WHITE   4   NA  Salmonellosis M WHITE

我尝试在 R 中粘贴,但找不到忽略最后两列的方法

此外,列数会随着我的应用程序中的每次迭代而变化,因此我需要一个忽略最后两列的函数,而不是选择几个前导列

这不是一个优雅的解决方案,但根据您的数据,您可以简单地使用 apply 并传入您的 data.frame 并通过动态引用列数来删除最后两列.

df = readr::read_table2("DISEASE Gender  Race    Freq    NEWCOL
Salmonellosis   M   RACE_LATINO_HISPANIC    1   NA
Salmonellosis   F   BLACK_AFRICAN_AMERICAN  2   NA
Salmonellosis   M   WHITE   3   NA
Salmonellosis   M   WHITE   4   NA")

df$Concat = apply(df[,1:(ncol(df)-2)],1,paste,collapse=" ")

tidyr 包有一个方便的 unite 函数来执行此合并:

df<-read.table(header = TRUE, text="DISEASE Gender  Race    Freq    NEWCOL
Salmonellosis   M   RACE_LATINO_HISPANIC    1   NA
Salmonellosis   F   BLACK_AFRICAN_AMERICAN  2   NA
Salmonellosis   M   WHITE   3   NA
Salmonellosis   M   WHITE   4   NA")


library(tidyr)
answer<-unite(df, concat, -c("Freq", "NEWCOL"), sep = " ", remove=FALSE)

#or to select by only the number of columns
unite(df, concat, 1:(ncol(df)-2), sep = " ", remove=FALSE)

或者我们可以使用interaction

df$concat <- interaction(df[head(names(df), -2)], sep= " ")

paste 来自 base R

df$concat <- do.call(paste, df[head(names(df), -2)])