r中的条件级联。
key key1 col1 col2 col3
cust1 k1 NA NA 34
cust2 k2 12 NA 24
Cust3 k3 1 23 34
。
cols <- names(df[3:ncol(df)])
df[, col4 := do.call(paste,c(lapply(cols, function(x) paste(x, get(x), sep=":")),sep="&&"))]
在这种情况下,我正在获取列名和列值,但是我只想为非null值做同样的事情 相应的输出
key key1 col1 col2 col3 col4
cust1 k1 NA NA 34 col1:NA&&col2:NA&&col3:34
cust2 k2 12 NA 24 col1:12&&col2:NA&&col3:24
Cust3 k3 1 23 34 col1:1&&col2:23&&col3:34
所需的输出
key key1 col1 col2 col3 col4
cust1 k1 NA NA 34 col3:34
cust2 k2 12 NA 24 col1:12&&col13:24
Cust3 k3 1 23 34 col1:1&&col2:23&&col3:34
答案 0 :(得分:2)
遵循@Ronak Sha的回答策略,这是与您在问题中使用的data.table
语法的集成:
a[,
col4 := apply(.SD,
1,
function(x) paste(names(x)[!is.na(x)],
x[!is.na(x)],
sep = ":",
collapse = "&&")),
.SDcols = 3:5]
a
key key1 col1 col2 col3 col4
1: cust1 k1 NA NA 34 col3:34
2: cust2 k2 12 NA 24 col1:12&&col3:24
3: Cust3 k3 1 23 34 col1:1&&col2:23&&col3:34
a <- fread("key key1 col1 col2 col3
cust1 k1 NA NA 34
cust2 k2 12 NA 24
Cust3 k3 1 23 34 ")
答案 1 :(得分:1)
我们可以逐行使用apply
,删除NA
值,然后将sep
参数添加为:
,并通过collapse
&&
>
cols <- grep("col", names(df))
df$col4 <- apply(df[cols], 1, function(x) {
x <- x[!is.na(x)]
paste(names(x), x, sep = ":", collapse = "&&")
})
df
# key key1 col1 col2 col3 col4
#1 cust1 k1 NA NA 34 col3:34
#2 cust2 k2 12 NA 24 col1:12&&col3:24
#3 Cust3 k3 1 23 34 col1:1&&col2:23&&col3:34
数据
df <- "Cust3"), class = "factor"), key1 = structure(1:3, .Label = c("k1",
"k2", "k3"), class = "factor"), col1 = c(NA, 12L, 1L), col2 = c(NA,
NA, 23L), col3 = c(34L, 24L, 34L)), class = "data.frame", row.names = (NA, -3L))