考虑到一个数据帧的因子水平和另一个数据帧的列名使用r
问题描述:
我需要为现有数据框创建一个考虑因素水平的新列。我有2个数据框叫做dat_group和dat_prices。这些数据框如下所示。考虑到一个数据帧的因子水平和另一个数据帧的列名使用r
dat_group
Group
1 A
2 A
3 A
4 A
5 A
6 A
7 A
8 A
9 A
10 A
11 C
12 C
13 C
14 C
15 C
16 C
17 C
18 C
19 C
20 C
21 B
22 B
23 B
24 B
25 B
26 B
27 B
28 B
29 B
30 B
dat_price
A B C
1 21 45 24
2 21 45 24
3 21 45 24
4 21 45 24
5 15 11 10
6 15 11 10
7 15 11 10
8 20 13 55
9 20 13 55
10 20 13 55
我需要粘贴A,B和C柱的考虑dat_group水平的值。行序列应该是相同的顺序。如果我创建新的列为dat_group作为“价格”
dat_group$Price<-NA
然后数据帧应该像;
Group Price
1 A 21
2 A 21
3 A 21
4 A 21
5 A 15
6 A 15
7 A 15
8 A 20
9 A 20
10 A 20
11 C 24
12 C 24
13 C 24
14 C 24
15 C 10
16 C 10
17 C 10
18 C 55
19 C 55
20 C 55
21 B 45
22 B 45
23 B 45
24 B 45
25 B 11
26 B 11
27 B 11
28 B 13
29 B 13
30 B 13
我试图做到这一点使用一些可用的例子e.g.1e.g.2,但没有奏效。
请任何人都可以帮助我。这两个示例数据帧可以通过以下代码访问。我的实际数据集有几千行。
dat_group<- structure(list(Group = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("A", "B", "C"), class = "factor")), .Names = "Group", class = "data.frame", row.names = c(NA,
-30L))
dat_price<-structure(list(A = c(21L, 21L, 21L, 21L, 15L, 15L, 15L, 20L,
20L, 20L), B = c(45L, 45L, 45L, 45L, 11L, 11L, 11L, 13L, 13L,
13L), C = c(24L, 24L, 24L, 24L, 10L, 10L, 10L, 55L, 55L, 55L)), .Names = c("A",
"B", "C"), class = "data.frame", row.names = c(NA, -10L))
答
为您的问题提供更具防御性的解决方案。希望即使您的所有因素水平都不是相同的倍数,这也是可行的。
library(dplyr); library(purrr); library(magrittr)
dat_group$original_order <- seq(1:nrow(dat_group))
dat_group %<>%
split(.$Group) %>%
map(~ mutate(., Price = rep(na.omit(dat_price[,unique(Group)]), n()/length(na.omit(dat_price[,unique(Group)]))))) %>%
bind_rows() %>%
arrange(original_order) %>%
select(-original_order)
dat_group
Group Price
1 A 21
2 A 21
3 A 21
4 A 21
5 A 15
6 A 15
7 A 15
8 A 20
9 A 20
10 A 20
11 C 24
12 C 24
13 C 24
14 C 24
15 C 10
16 C 10
17 C 10
18 C 55
19 C 55
20 C 55
21 B 45
22 B 45
23 B 45
24 B 45
25 B 11
26 B 11
27 B 11
28 B 13
29 B 13
30 B 13
原件(懒惰)解决方案:
dat_group$Price <- rep(unlist(dat_price), length.out = nrow(dat_group))
答
library(data.table)
dat_price <- as.data.table(dat_price)
dat_price_new <- cbind(dat_price[, c(1,3), with = FALSE],
dat_price[, 2, with = FALSE])
melt(dat_price_new)
+0
此代码对于我的实际数据集不可行,因为我的实际数据集中的级别发生超过50次。 – sriya
如果只有2个'A',再接2'B's等。在这种情况下应该输出什么?或者后果因素的数量是否与'dat_price'行相同? –