繁体   English   中英

从 dataframe 中的列中提取唯一数字

[英]extract unique numbers from column in a dataframe

我想从数据框中的列中提取唯一数字。 我已经从不同的列中提取了数字,并进入了数据框中的不同列。 示例代码:

library(dplyr)
df <- as.data.frame(rbind(c("12,15,19,15,12,16,41"),c("1,2,3,4,5,4,3,2,1")))
df1 <- unique(df)

预期的 output 是:

12,15,19,16,41  
1,2,3,4,5

您可以在 dataframe 中创建一个列表列,不确定这是否是您想要的:

list_col <- lapply(
  strsplit(as.character(df$V1), ","), 
  function(x) as.numeric(unique(x))
)

df1 <- data.frame(I(list_col))
df1
#       list_col
# 1 12, 15, ....
# 2 1, 2, 3,....

df1$list_col
# [[1]]
# [1] 12 15 19 16 41
#
# [[2]]
# [1] 1 2 3 4 5

我们可以用逗号 ( , ) 分割字符串,并只从每个字符串中提取unique值。

df$new_col <- sapply(strsplit(df$V1, ","), function(x) toString(unique(x)))
df

#                    V1            new_col
#1 12,15,19,15,12,16,41 12, 15, 19, 16, 41
#2    1,2,3,4,5,4,3,2,1      1, 2, 3, 4, 5
df <- as.data.frame(rbind(c("12,15,19,15,12,16,41"),c("1,2,3,4,5,4,3,2,1")))

x <- apply(df, 1, function(x) eval(parse(text=paste0("c(", x, ")"))) )
sapply(x, function(x) as.numeric(unique(x)))

返回

      [,1] [,2]
[1,]   12    1
[2,]   15    2
[3,]   19    3
[4,]   16    4
[5,]   41    5

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM