r - 在 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]), ]
但这切断了匹配的唯一字符串数量的表格。
任何帮助将不胜感激。谢谢你。
解决方案
一个选项是循环遍历行、replace
元素duplicated
到NA
,然后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))
推荐阅读
- amazon-web-services - 谁删除了 S3 存储桶中的文件?
- c++ - LNK2019 在项目目录内的文件中使用 glewInit
- r - R中数值的温度数据栅格堆栈
- amazon-web-services - 自动化 API 网关阶段部署
- ios - iOS:检查手机是否为双卡?
- android - 如果应用程序没有使用调试按钮启动,为什么 BuildConfig.DEBUG 仍然为真?
- html - HTML CSS 表格边框半径属性不适用
- windows - 在 Cygwin 中安装 Jupyter Lab 时获取纱线配置失败
- python-3.x - Python + Mechanize - 使用 POST 模拟 Javascript 按钮单击?
- angular - 比较 2 不同结构的 Observable