![](/img/trans.png)
[英]How to rowwise select random elements in a tibble via dplyr in R?
[英]Rowwise mutation of tibble without for loop in R
我有两个 tibble,需要在一个 tibble 中索引数据,并根据第一个 tibble 中的变量在另一个 tibble 中插入一些特定数据。
我有两个问题:
library(dplyr)
# Set seed
set.seed(10)
# Get data
df1 <- starwars %>%
select(name,species) %>%
filter(species %in% c("Human","Wookiee","Droid")) %>%
mutate(Fav_colour = sample(c("blue","red","green"),n(),replace=TRUE))
# Random table with typical colour preference
df2 <- tibble(Colour = c("blue","green","red"),
Human = c(0.5,0.3,0.1),
Wookiee = c(0.2,0.8,0.5),
Droid = c(0.3,0.1,0.5))
在 df1 中,我需要根据物种插入典型的颜色偏好。 为此,我可以在 for 循环中遍历 tibble 的每一行,添加相关数据,然后编译成一个列表。
# Make empty list
data <- list()
# Iterate through each row
for (x in 1:nrow(df1)) {
# Take a slice
tmp <- slice(df1, x)
# Add new column to slice based on data in slice (species)
tmp$Typical <- df2 %>%
select(Colour,tmp$species) %>%
arrange(desc(.data[[tmp$species]])) %>%
slice_head(n = 1) %>%
select(Colour) %>%
as.character()
#Add data to list
data[[x]] <- tmp
}
#Recompile df1
df1 <- list.rbind(data)
我认为必须有一种更有效的方法来执行此操作,但无法弄清楚如何在不通过 for 循环的情况下从 df2 获取过滤和排列的值。 我不知道该怎么做,但是使用 function 可能是更好的选择吗? 没有 for 循环的 dplyr 方法是什么?
听起来你想从df2
中获得每个物种的最大价值。 如果我们pivot_longer
使物种在一列中指定,而值在另一列中指定,我们可以按物种分组并保留最大值。 这个查找表(每个物种的颜色 + 值)可以连接到原始数据。
df1 %>%
left_join(
df2 %>%
tidyr::pivot_longer(2:4, names_to = "species") %>%
group_by(species) %>%
slice_max(value)
)
结果
Joining with `by = join_by(species)`
# A tibble: 43 × 5
name species Fav_colour Colour value
<chr> <chr> <chr> <chr> <dbl>
1 Luke Skywalker Human green blue 0.5
2 C-3PO Droid blue red 0.5
3 R2-D2 Droid red red 0.5
4 Darth Vader Human green blue 0.5
5 Leia Organa Human red blue 0.5
6 Owen Lars Human green blue 0.5
7 Beru Whitesun lars Human green blue 0.5
8 R5-D4 Droid green red 0.5
9 Biggs Darklighter Human green blue 0.5
10 Obi-Wan Kenobi Human green blue 0.5
# … with 33 more rows
# ℹ Use `print(n = ...)` to see more rows
请检查不使用循环的替代方法,检查 df4 dataframe
df3 <- df2 %>%
pivot_longer(c('Human','Wookiee','Droid'),names_to = 'species', values_to = 'score') %>%
arrange(species, desc(score)) %>%
group_by(species) %>% slice(1)
df4 <- df1 %>% left_join(df3, by='species') %>% rename(Typical = Colour) %>% select(-score)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.