我有一個df六列 ( a,b,c,d,e,f)
我隨機選擇這六個字母之一并將其分配給一個額外的列:
df %>% mutate(ran=sample(c("a","b","c","d","e","f"),n(), replace=T))
所以對于每一行我有一個隨機選擇的列名。如何獲取相應隨機選取的列的值并將其放入新列?
uj5u.com熱心網友回復:
這是一個依賴于 tidyverse 的解決方案tidyr::gather。
首先,我創建了一個示例標題。
library(tidyverse)
set.seed(123)
df <-
tibble(a = 1:5, b = a 10, c = b 10, d = c 10, e = d 10, f = e 10) %>%
mutate(
ran=sample(c("a","b","c","d","e","f"),n(), replace=T),
row = 1:n()
)
然后我旋轉這個資料框,然后filter用來選擇正確的值。
df %>%
gather(val, col, -ran, -row) %>%
filter(ran==val) %>%
select(row, col) %>%
left_join(df, ., by = "row")
# A tibble: 5 x 9
a b c d e f ran row col
<int> <dbl> <dbl> <dbl> <dbl> <dbl> <chr> <int> <dbl>
1 1 11 21 31 41 51 c 1 21
2 2 12 22 32 42 52 f 2 52
3 3 13 23 33 43 53 c 3 23
4 4 14 24 34 44 54 b 4 14
5 5 15 25 35 45 55 b 5 15
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/315283.html
下一篇:將串列串列轉換為資料框列
