R将每个数据框元素转换为多个n元素

时间:2018-08-02 10:31:34

标签: r dataframe

我有一个数据帧(df),它具有每年的大气沉积值,矢量是12个元素(mul)。

str(df) 'data.frame':   220 obs. of  11 variables: 
$ year : num  1900 1902 1903 1904 1906 ...
$ BOX1 : num  0.72 0.72 0.72 0.72 0.72 ...  

mul <- c(0.7,0.7,1.3,1.7,0.7,1.0,0.7, 1.7,1.7,1.7,1.0,0.4)

我想将给定列'BOX'的每个元素乘以'mul'的12值,以使220个元素列变成2640个元素列。 在下面的示例中,我已经对BOX1列的第一个元素执行了此操作,但是我需要一次将过程应用于所有元素。

df$BOX1[1] * mul

[1] 0.503811 0.503811 0.935649 1.223541 0.503811 0.719730 0.503811 1.223541 1.223541 1.151568 0.719730 0.287892

谢谢您的帮助

2 个答案:

答案 0 :(得分:0)

# example data
df = data.frame(year = c(1900,1902,1903),
                BOX1 = c(0.72, 0.75, 0.80))

mul <- c(0.7,0.7,1.3,1.7,0.7,1.0,0.7, 1.7,1.7,1.7,1.0,0.4)

library(tidyverse)

df %>%
  rowwise() %>%                       # for each row
  mutate(x = list(BOX1 * mul)) %>%    # multiply value in BOX1 with mul and save results as a list
  unnest()                            # unnest data

# # A tibble: 36 x 3
#    year  BOX1     x
#   <dbl> <dbl> <dbl>
# 1  1900  0.72 0.504
# 2  1900  0.72 0.504
# 3  1900  0.72 0.936
# 4  1900  0.72 1.22 
# 5  1900  0.72 0.504
# 6  1900  0.72 0.72 
# 7  1900  0.72 0.504
# 8  1900  0.72 1.22 
# 9  1900  0.72 1.22 
# 10 1900  0.72 1.22 
# # ... with 26 more rows

如果需要,您可以删除列BOX1

您也可以尝试使用向量化函数代替rowwise,这可能会更快:

# vectorised function to multiply vectors
f = function(x,y) x*y
f = Vectorize(f)

df %>%
  mutate(x = list(f(BOX1, mul))) %>%    
  unnest() 

答案 1 :(得分:0)

tidyverse的另一种解决方案:

library(tidyr)
library(dplyr)
library(tibble)

mul %>% as.data.frame %>% rowid_to_column %>%  # to keep duplicates in 'mul'
   crossing(df) %>% mutate(v=BOX1*mul)         # when calling 'crossing'