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

人走茶凉 提交于 2019-12-09 03:23:47

问题


New to R, please guide !

Dataframe1 contain:

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 contain one row with each parameters as field names: df2 = A B C D E F g .....'n'

Example Output (if values not found the null to be printed):

df2:
A  B  C  D   E   F   G
5     1      5   4   2
6  3     6   4   4
   2  3  3   3   7

How to populate values of each parameter from df1 to df2 under same parameter which are present in first row as fields?


回答1:


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))


来源:https://stackoverflow.com/questions/49377966/how-to-populate-parameters-values-present-in-rows-of-one-dataframedf1-to-dataf

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