将数据映射到数据框中的列的更好方法?

时间:2018-12-12 18:14:34

标签: r dplyr

我需要合并多个大型数据框,有时会添加一个唯一的可识别列以进行合并。我使用这种方法有效,但似乎需要很长时间。基本上,使用dplyr,我抓取了一个变量的distinct返回,然后为每个变量mutate一个新变量,然后merge将该变量返回到原始数据帧。有没有更好的方法可以做到这一点?

df <- tibble(
  x = rep(LETTERS, 10)
)


df %>% 
  distinct(x) %>% 
  mutate(y = 1:nrow(.)) %>% 
  right_join(df)

2 个答案:

答案 0 :(得分:3)

我们可以使用angular.element(function () { document.getElementById("gridId").src = document.location.protocol + '//' + document.location.hostname + ':8888/myPage.aspx?' + window.location.search.substr(1); });

match

或带有library(dplyr) df %>% mutate(y = match(x, unique(x)))

factor

或与df %>% mutate(y = as.integer(factor(x, levels = unique(x))))

group_indices

答案 1 :(得分:1)

由于您没有指定是否需要dplyr,因此这是data.table方法:

setDT(df)[, y := .GRP, by=x]

或简单地在基数R中

df$y = as.integer(factor(df$x))
相关问题