我正在使用R.我想将DataFrame-1
转换为DataFrame-2
DataFrame-1
Variable1 Variable2
aa1 X1
aa1 Y2
aa1 Z1
bb1 Y1
bb1 Y2
我想创建DataFrame-2
,看起来像这样
Variable1 Variable2
aa1 X1, Y2, Z1
bb1 Y1, Y2
答案 0 :(得分:0)
也许是这样的?
type DateTime=String
val la = List (ImageMetadata("12", "im 1 foo"), ImageMetadata ("13", "im 2 bar"), ImageMetadata ("23", "im 3 bar"))
val lb = List (ObjectMetadata("23", List ("o", "1")), ObjectMetadata ("12", List("o", "2")), ObjectMetadata ("17", List("o", "3")))
for (i <- la;
o <- lb;
if (i.time == o.time)) yield { ImageTypeMetadata (i.time, i.name, o.tags)}
res12: List[ImageTypeMetadata] = List(ImageTypeMetadata(12,im 1 foo,List(o, 2)), ImageTypeMetadata(23,im 3 bar,List(o, 1)))
答案 1 :(得分:0)
希望这有帮助!
library(dplyr)
df1 <- df %>%
group_by(Variable1) %>%
summarise(Variable2 = paste(Variable2, collapse = ", ")) %>%
data.frame()
df1
输出是:
Variable1 Variable2
1 aa1 X1, Y2, Z1
2 bb1 Y1, Y2
示例数据:
df <- structure(list(Variable1 = c("aa1", "aa1", "aa1", "bb1", "bb1"
), Variable2 = c("X1", "Y2", "Z1", "Y1", "Y2")), .Names = c("Variable1",
"Variable2"), class = "data.frame", row.names = c(NA, -5L))
答案 2 :(得分:0)
这是cars
数据集的示例:
split <- split(cars$dist, cars$speed)
a <- list(length(split))
for (i in 1:length(split)){
a[i] = paste(split[[i]], sep = "", collapse = ", ")}
df <- data.frame(x = labels(split), y = unlist(a))
输出如下:
x y
1 4 2, 10
2 7 4, 22
3 8 16
4 9 10
5 10 18, 26, 34
6 11 17, 28
7 12 14, 20, 24, 28
8 13 26, 34, 34, 46
9 14 26, 36, 60, 80
10 15 20, 26, 54
11 16 32, 40
12 17 32, 40, 50
13 18 42, 56, 76, 84
14 19 36, 46, 68
15 20 32, 48, 52, 56, 64
16 22 66
17 23 54
18 24 70, 92, 93, 120
19 25 85
答案 3 :(得分:0)
使用spread
和unite
作为:
library(tidyverse)
DataFrame1 %>% mutate(sl = row_number()) %>%
spread(sl, Variable2, fill = "") %>%
unite(col = "Variable2",-Variable1, sep = ",") %>%
mutate(Variable2 = gsub("^,+|,+$", "", Variable2))
Variable1 Variable2
1 aa1 X1,Y2,Z1
2 bb1 Y1,Y2
数据强>
DataFrame1 <- read.table(text = "Variable1 Variable2
aa1 X1
aa1 Y2
aa1 Z1
bb1 Y1
bb1 Y2", header = TRUE, stringsAsFactor = FALSE)