使用R将值移到data.frame的左侧 [英] Using R to shift values to the left of data.frame

查看:67
本文介绍了使用R将值移到data.frame的左侧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Okay, so I have this 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行为例.

And I am interested in taking all the missing values from the first columns and replace them with the values over from the other columns, as an example with rows 2, 4, 5 and 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列中有4列和2个值怎么办和3个是NA.有没有人知道可能有效的算法?

My idea was to loop over the columns to grab the rows with the missing values and replace them with the values in the column to the right but that is also potentially flawed because what if there were 4 columns and two values in columns 2 and 3 were NA. Does anyone have an idea of an algorithm that may work?

推荐答案

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

We can loop over the rows and concatenate the non-NA elements followed by the NA elements and assign it back to the dataset

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")

这篇关于使用R将值移到data.frame的左侧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆