即使值的数量不同,如何将数据框列中的唯一值获取到数据框中 [英] How can I get unique values in dataframe column into a dataframe even though the number of values is not the same

查看:39
本文介绍了即使值的数量不同,如何将数据框列中的唯一值获取到数据框中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框数据:

Data <- data.frame(A=sample(1:7),B=c(5,5,5,6,6,6,6),C=c(1,2,2,3,3,4,5))
  A B C
1 6 5 1
2 7 5 2
3 4 5 2
4 2 6 3
5 1 6 3
6 5 6 4
7 3 6 5    


每列都有一组不同的唯一值和数量。

I am trying to extract the unique values from each of the columns into a data.frame. Each column has a different set and number of unique values.

我正在寻找类似的东西:

I am looking for something like:

A  1   2   3   4   5   6   7 
B  5   6   NA  NA  NA  NA  NA
C  1   2   3   4   5   NA  NA

我能够遍历它并获取包含信息的列表(我尝试使用列表是因为它们的长度不同)

I was able to loop through it and get a list with the information (I tried using a list because they are of different length)

vars <- c('A','B','C')
mylist = vector("list",length(vars))
for(i in 1: length(vars)){
   mylist[[i]] <- c( names(table( Data[ , vars[i] ] )))
}

如何将信息放入data.frame ,理想情况下没有循环?
谢谢!

How can I get the information into a data.frame, ideally without a loop? Thanks!

推荐答案

lapply()这个。这是我使用的技巧。

lapply() is sufficient for this. Here's the trick I use.

xx <- lapply(Data, unique)
data.frame(do.call(rbind, lapply(xx, "length<-", max(vapply(xx, length, 1L)))))
#   X1 X2 X3 X4 X5 X6 X7
# A  2  3  6  5  1  7  4
# B  5  6 NA NA NA NA NA
# C  1  2  3  4  5 NA NA

首先,我们遍历 Data 的列以查找所有唯一值。然后我们进行迭代,使用 length <-将每个元素的长度扩展到 xx 最长的长度元件。然后,我们将它们全部整合到一个数据框中。

First, we iterate over the columns of Data to find all unique values. Then we iterate that, using length<- to extend the length of each element to the length of xx's longest element. Then we just bring it all together into a data frame.

这篇关于即使值的数量不同,如何将数据框列中的唯一值获取到数据框中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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