我们可以使用dplyr/tidyr。我们使用gather将数据从“宽”重塑为“长”,使用filter删除“Val”列中的空白元素,并使用spread将其重塑回“宽”格式。
library(dplyr)
library(tidyr)
gather(mydata, Var, Val, V3:V5) %>%
filter(Val!='') %>%
spread(Var, Val)
# V1 V2 V3 V4 V5
#1 a b a c d
#2 x y h k e
或仅使用dplyr 的另一种方法(如果每个组中非空白值的数量相同)将按“V1”、“V2”分组,并使用summarise_each 仅选择元素非空白 (.[.!=''])
mydata %>%
group_by(V1, V2) %>%
summarise_each(funs(.[.!='']))
# V1 V2 V3 V4 V5
#1 a b a c d
#2 x y h k e
我们也可以使用data.table 来执行此操作。我们将“data.frame”转换为“data.table”(setDT(mydata)),按“V1”、“V2”分组,遍历其他列(lapply(.SD, ...))并对非空白元素进行子集化。
library(data.table)
setDT(mydata)[,lapply(.SD, function(x) x[x!='']) ,.(V1, V2)]
# V1 V2 V3 V4 V5
#1: a b a c d
#2: x y h k e
使用来自base R 的aggregate 的类似方法是
aggregate(.~V1+V2, mydata, FUN=function(x) x[x!=''])
# V1 V2 V3 V4 V5
#1 a b a c d
#2 x y h k e
数据
mydata <- structure(list(V1 = c("a", "a", "a", "x", "x"),
V2 = c("b", "b",
"b", "y", "y"), V3 = c("a", "", "", "h", ""), V4 = c("", "c",
"", "", "k"), V5 = c("", "", "d", "", "e")), .Names = c("V1",
"V2", "V3", "V4", "V5"), class = "data.frame", row.names = c("1",
"2", "3", "4", "5"))