How to populate parameters values present in rows of one dataframe(df1) to dataframe(df2) under same parameter field in R

杀马特。学长 韩版系。学妹 提交于 2019-12-01 10:33:55

Create a row number column (rownames_to_column), gather into 'long' format, separate the 'val' column into two (by splitting at =- automatically picked up) and then spread into 'wide' format. By default, the elements that are missing are filled by NA. There is also a fill argument to change it to the desired fill value

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>

If there is a second dataset containing some values and want to replace the non-NA elements in 'df2'

df2[!is.na(df2)] <-  res[!is.na(df2)][names(df2)]

Or another option is dcast from 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

data

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))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!