小编典典

使用R将值移到data.frame的左侧

algorithm

好的,所以我有这个data.frame:

        A      B      C
1  yellow purple   <NA>
2    <NA>   <NA> yellow
3  orange yellow   <NA>
4  orange   <NA>  brown
5    <NA>  brown purple
6  yellow purple   pink
7  purple  green   pink
8  yellow   pink  green
9  purple orange   <NA>
10 purple   <NA>  brown

我有兴趣从第一列中获取所有缺失的值,并用其他列中的值替换它们,例如,以第2、4、5和10行为例。

        A      B      C
1  yellow purple   <NA>
2  yellow   <NA>   <NA>
3  orange yellow   <NA>
4  orange  brown   <NA>
5   brown purple   <NA>
6  yellow purple   pink
7  purple  green   pink
8  yellow   pink  green
9  purple orange   <NA>
10 purple  brown   <NA>

我的想法是循环遍历各列以获取缺少值的行,并用右侧列中的值替换它们,但这也可能存在缺陷,因为如果有4列,而第2和3列中有两个值,那该怎么办?不适用
有谁知道可能有效的算法?


阅读 251

收藏
2020-07-28

共1个答案

小编典典

我们可以遍历行并连接非NA元素和NA元素,然后将其分配回数据集

df[] <-  t(apply(df, 1, function(x) c(x[!is.na(x)], x[is.na(x)])))
df
#        A      B     C
#1  yellow purple  <NA>
#2  yellow   <NA>  <NA>
#3  orange yellow  <NA>
#4  orange  brown  <NA>
#5   brown purple  <NA>
#6  yellow purple  pink
#7  purple  green  pink
#8  yellow   pink green
#9  purple orange  <NA>
#10 purple  brown  <NA>

数据

df <- structure(list(A = c("yellow", NA, "orange", "orange", NA, "yellow", 
"purple", "yellow", "purple", "purple"), B = c("purple", NA, 
"yellow", NA, "brown", "purple", "green", "pink", "orange", NA
 ), C = c(NA, "yellow", NA, "brown", "purple", "pink", "pink", 
 "green", NA, "brown")), .Names = c("A", "B", "C"), row.names = c("1", 
 "2", "3", "4", "5", "6", "7", "8", "9", "10"), class = "data.frame")
2020-07-28