将多个具有大量NA的列合并到R中的一个因子列中 [英] Combining multiple columns with a lots of NA into one factor column in R

查看:321
本文介绍了将多个具有大量NA的列合并到R中的一个因子列中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有观察结果的.csv导入表格。

  ED1 ED2 ED3 ED4 ED5 
1 NA NA NA NA
NA NA 1 NA NA
NA 1 NA NA NA
NA NA NA NA 1

< ----- etc. ------>



所以每一行只包含一个值1一行中的列包含NA。我需要将这五列合并为一个因子列。



像:



EDU < kbd>



2



p>

3



1



2



也许这可能是一个因子列,其中包含因子ED1,ED2,ED3等(作为源列的名称)。

解决方案

这里不需要使用 apply()循环。您可以使用 max.col()结合对 is.na()的否定调用。

  max.col(!is.na(df))
#[1] 1 3 2 5

这给出了1的列号。要获取列名,我们可以在数据框架的 names()的向量子集中使用它。

  names(df)[max.col(!is.na(df))] 
#[1]ED1ED3ED2ED5

因此,我们可以通过执行

$ b $来获得所需的数据框b

  data.frame(EDU = names(df)[max.col(!is.na(df))])
#EDU
#1 ED1
#2 ED3
#3 ED2
#4 ED5

数据

  df < (NA,NA,NA,NA),ED2 = c(NA,NA,1,NA),
ED3 = c ),ED5 = c(NA,
NA,NA,1)),.Names = c(ED1,ED2,ED3,ED4,ED5 row.names = c(NA,-4L),class =data.frame)


I have a .csv imported table with observations.

ED1 ED2 ED3 ED4 ED5 
1   NA  NA  NA  NA 
NA  NA  1   NA  NA 
NA  1   NA  NA  NA 
NA  NA  NA  NA  1 

<----- etc. ------>

So every row contains only one value "1", other columns in one row contains NA. I need to combine this five columns into one factor column.

Like:

EDU

2

3

3

1

2

1

Or maybe this could be a factor column with factors "ED1", "ED2", "ED3" etc. (as the names of source columns).

解决方案

There is no need to use an apply() loop here. You could use max.col() in combination with a negated call to is.na().

max.col(!is.na(df))
# [1] 1 3 2 5

That gives us the column numbers where the 1s are. To get the column names, we can use that in a vector subset of the names() of the data frame.

names(df)[max.col(!is.na(df))]
# [1] "ED1" "ED3" "ED2" "ED5"

So we can get the desired data frame, with factor column, by doing

data.frame(EDU = names(df)[max.col(!is.na(df))])
#   EDU
# 1 ED1
# 2 ED3
# 3 ED2
# 4 ED5

Data:

df <- structure(list(ED1 = c(1, NA, NA, NA), ED2 = c(NA, NA, 1, NA), 
    ED3 = c(NA, 1, NA, NA), ED4 = c(NA, NA, NA, NA), ED5 = c(NA, 
    NA, NA, 1)), .Names = c("ED1", "ED2", "ED3", "ED4", "ED5"
), row.names = c(NA, -4L), class = "data.frame")

这篇关于将多个具有大量NA的列合并到R中的一个因子列中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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