首页 > 解决方案 > 在 R 中跨列保留字符串的第一个实例

问题描述

我有一个看起来像这样的表:

step1  |  step2  |  step3  |  step4
A          A         B         C
A          A         NA        NA

我想要实现的是这个

step1  |  step2  |  step3  |  step4
A     |     B    |     C    |     NA
A     |    NA     |    NA     |    NA

我尝试先转置然后运行它

table4 <- table3[match(unique(table3[,1]), table3[,1]), ]

但这切断了匹配的唯一字符串数量的表格。

任何帮助将不胜感激。谢谢你。

标签: r

解决方案


一个选项是循环遍历行、replace元素duplicatedNA,然后order通过缺失值,转置输出并将其分配给原始数据

table3[] <- t(apply(table3, 1, function(x) {
         x1 <- replace(x, duplicated(x), NA)
         x1[order(is.na(x1))]}))
table3
#  step1 step2 step3 step4
#1     A     B     C  <NA>
#2     A  <NA>  <NA>  <NA>

数据

table3 <- structure(list(step1 = c("A", "A"), step2 = c("A", "A"), 
    step3 = c("B", NA), step4 = c("C", NA)), .Names = c("step1", 
  "step2", "step3", "step4"), class = "data.frame", row.names = c(NA, -2L))

推荐阅读