如何将存在于一个数据帧(df1)行中的参数值填充到R中相同参数字段下的数据帧(df2)
How to populate parameters values present in rows of one dataframe(df1) to dataframe(df2) under same parameter field in R
R新手,求指导!
Dataframe1 包含:
df1
Col1 Col2 Col3 Col4 Col5
A=5 C=1 E=5 F=4 G=2 --Row1
A=6 B=3 D=6 E=4 F=4 --Row2
B=2 C=3 D=3 E=3 F=7 --Row3
Dataframe2 包含一行,每个参数作为字段名称:
df2 = A B C D E F g .....'n'
示例输出(如果未找到要打印的空值):
df2:
A B C D E F G
5 1 5 4 2
6 3 6 4 4
2 3 3 3 7
如何在同一参数下填充从 df1 到 df2 的每个参数的值,这些值作为字段出现在第一行中?
创建一个行号列(rownames_to_column
),gather
成'long'格式,separate
将'val'列一分为二(通过拆分在=
-自动拾取)然后spread
变成'wide'格式。默认情况下,缺少的元素由 NA
填充。还有一个 fill
参数可以将其更改为所需的填充值
library(tidyverse)
res <- df1 %>%
rownames_to_column('rn') %>%
gather(key, val, -rn) %>%
separate(val, into = c('val1', 'val2')) %>%
select(-key) %>%
spread(val1, val2) %>%
select(-rn)
res
# A B C D E F G
#1 5 <NA> 1 <NA> 5 4 2
#2 6 3 <NA> 6 4 4 <NA>
#3 <NA> 2 3 3 3 7 <NA>
如果有第二个数据集包含一些值并且想要替换 'df2'
中的 non-NA 元素
df2[!is.na(df2)] <- res[!is.na(df2)][names(df2)]
或者另一个选项是 dcast
来自 data.table
library(data.table)
dcast(setDT(df1)[, tstrsplit(unlist(.SD), "="), .(grp = 1:nrow(df1))
], grp ~ V1, value.var = 'V2')[, grp := NULL][]
# A B C D E F G
#1: 5 NA 1 NA 5 4 2
#2: 6 3 NA 6 4 4 NA
#3: NA 2 3 3 3 7 NA
数据
df1 <- structure(list(Col1 = c("A=5", "A=6", "B=2"), Col2 = c("C=1",
"B=3", "C=3"), Col3 = c("E=5", "D=6", "D=3"), Col4 = c("F=4",
"E=4", "E=3"), Col5 = c("G=2", "F=4", "F=7")), .Names = c("Col1",
"Col2", "Col3", "Col4", "Col5"), class = "data.frame", row.names = c(NA,
-3L))
R新手,求指导!
Dataframe1 包含:
df1
Col1 Col2 Col3 Col4 Col5
A=5 C=1 E=5 F=4 G=2 --Row1
A=6 B=3 D=6 E=4 F=4 --Row2
B=2 C=3 D=3 E=3 F=7 --Row3
Dataframe2 包含一行,每个参数作为字段名称: df2 = A B C D E F g .....'n'
示例输出(如果未找到要打印的空值):
df2:
A B C D E F G
5 1 5 4 2
6 3 6 4 4
2 3 3 3 7
如何在同一参数下填充从 df1 到 df2 的每个参数的值,这些值作为字段出现在第一行中?
创建一个行号列(rownames_to_column
),gather
成'long'格式,separate
将'val'列一分为二(通过拆分在=
-自动拾取)然后spread
变成'wide'格式。默认情况下,缺少的元素由 NA
填充。还有一个 fill
参数可以将其更改为所需的填充值
library(tidyverse)
res <- df1 %>%
rownames_to_column('rn') %>%
gather(key, val, -rn) %>%
separate(val, into = c('val1', 'val2')) %>%
select(-key) %>%
spread(val1, val2) %>%
select(-rn)
res
# A B C D E F G
#1 5 <NA> 1 <NA> 5 4 2
#2 6 3 <NA> 6 4 4 <NA>
#3 <NA> 2 3 3 3 7 <NA>
如果有第二个数据集包含一些值并且想要替换 'df2'
中的 non-NA 元素df2[!is.na(df2)] <- res[!is.na(df2)][names(df2)]
或者另一个选项是 dcast
来自 data.table
library(data.table)
dcast(setDT(df1)[, tstrsplit(unlist(.SD), "="), .(grp = 1:nrow(df1))
], grp ~ V1, value.var = 'V2')[, grp := NULL][]
# A B C D E F G
#1: 5 NA 1 NA 5 4 2
#2: 6 3 NA 6 4 4 NA
#3: NA 2 3 3 3 7 NA
数据
df1 <- structure(list(Col1 = c("A=5", "A=6", "B=2"), Col2 = c("C=1",
"B=3", "C=3"), Col3 = c("E=5", "D=6", "D=3"), Col4 = c("F=4",
"E=4", "E=3"), Col5 = c("G=2", "F=4", "F=7")), .Names = c("Col1",
"Col2", "Col3", "Col4", "Col5"), class = "data.frame", row.names = c(NA,
-3L))