连接不包含零的列
Concatenate columns if they don't contain a zero
我正在尝试将 4 Columns 连接到一个名为“标签”的列中,以供以后使用多标签分类。我想以一种只给出输出的方式连接列,粘贴不为零的列,然后用逗号分隔它们。
一个例子是最后一行的单元格是 {1,2} 而不是 {1,2,0,0}
我目前没有可按需运行的代码,也无法在 Internet 上找到相关内容。你们有做这件事的秘诀吗?
当前代码:
df$TV[df$TV==1] = '1'
df$Internet[df$Internet ==1] = '2'
df$Mobil[df$Mobil==1] = '3'
df$Fastnet[df$Fastnet==1] = '4'
df$tags = paste(df$TV,df$Internet,df$Mobil,df$Fastnet, sep=",")
Base R 选项使用 apply
-
cols <- c('TV', 'Internet', 'Mobil', 'Fastnet')
#df <- read.csv('stack.csv')
df$tags <- apply(df[cols], 1, function(x) toString(x[x!= 0]))
df
在dplyr
中我们可以使用rowwise
-
library(dplyr)
df <- df %>%
rowwise() %>%
mutate(tags = {
tmp <- c_across(all_of(cols))
toString(tmp[tmp != 0])
}) %>%
ungroup
df
我们可以使用 dapply
来自 collapse
library(collapse)
cols <- c('TV', 'Internet', 'Mobil', 'Fastnet')
df$tags <- dapply(slt(df, cols) MARGIN = 1, FUN = function(x) toString(x[x != 0]))
数据
df <- data.frame(TV = c(1, 3, 2, 0), Internet = c(1, 0, 1, 4), Mobil = c(0, 1, 3, 2), Fastnet = c(1, 5, 3, 2))
我正在尝试将 4 Columns 连接到一个名为“标签”的列中,以供以后使用多标签分类。我想以一种只给出输出的方式连接列,粘贴不为零的列,然后用逗号分隔它们。 一个例子是最后一行的单元格是 {1,2} 而不是 {1,2,0,0}
我目前没有可按需运行的代码,也无法在 Internet 上找到相关内容。你们有做这件事的秘诀吗?
当前代码:
df$TV[df$TV==1] = '1'
df$Internet[df$Internet ==1] = '2'
df$Mobil[df$Mobil==1] = '3'
df$Fastnet[df$Fastnet==1] = '4'
df$tags = paste(df$TV,df$Internet,df$Mobil,df$Fastnet, sep=",")
Base R 选项使用 apply
-
cols <- c('TV', 'Internet', 'Mobil', 'Fastnet')
#df <- read.csv('stack.csv')
df$tags <- apply(df[cols], 1, function(x) toString(x[x!= 0]))
df
在dplyr
中我们可以使用rowwise
-
library(dplyr)
df <- df %>%
rowwise() %>%
mutate(tags = {
tmp <- c_across(all_of(cols))
toString(tmp[tmp != 0])
}) %>%
ungroup
df
我们可以使用 dapply
来自 collapse
library(collapse)
cols <- c('TV', 'Internet', 'Mobil', 'Fastnet')
df$tags <- dapply(slt(df, cols) MARGIN = 1, FUN = function(x) toString(x[x != 0]))
数据
df <- data.frame(TV = c(1, 3, 2, 0), Internet = c(1, 0, 1, 4), Mobil = c(0, 1, 3, 2), Fastnet = c(1, 5, 3, 2))