从 R 数据帧列中提取键值对

use*_*216 2 r dataframe

我有一个包含两列的数据框。包含以分号分隔的键值对的 ID 列和字符列。

   ID | KeyValPairs
    1 | "zx=1; ds=4; xx=6"
    2 | "qw=5; df=2"
    . | ....
Run Code Online (Sandbox Code Playgroud)

我想把它变成一个包含三列的数据框

    ID | Key | Val
     1 | zx  | 1
     1 | ds  | 4
     1 | xx  | 6
     2 | qw  | 5
     2 | df  | 2
Run Code Online (Sandbox Code Playgroud)

KeyValPairs 列中没有固定数量的键值对,也没有可能的键的封闭集。我一直在寻找涉及循环和重新插入空数据帧的解决方案,但它无法正常工作,我被告知我应该避免在 R 中循环。

Pie*_*une 6

一个 tidyr 和 dplyr 方法:

整理

library(tidyr)
library(reshape2)
s <- separate(df, KeyValPairs, 1:3, sep=";")
m <- melt(s, id.vars="ID")
out <- separate(m, value, c("Key", "Val"), sep="=")
na.omit(out[order(out$ID),][-2])
#   ID Key Val
# 1  1  zx   1
# 3  1  ds   4
# 5  1  xx   6
# 2  2  qw   5
# 4  2  df   2
Run Code Online (Sandbox Code Playgroud)

dplyrish

library(tidyr)
library(dplyr)
df %>% 
  mutate(KeyValPairs = strsplit(as.character(KeyValPairs), "; ")) %>% 
  unnest(KeyValPairs) %>% 
  separate(KeyValPairs, into = c("key", "val"), "=")
#courtesy of @jeremycg
Run Code Online (Sandbox Code Playgroud)

数据

df <- structure(list(ID = c(1, 2), KeyValPairs = structure(c(2L, 1L
), .Label = c(" qw=5; df=2", " zx=1; ds=4; xx=6"), class = "factor")), .Names = c("ID", 
"KeyValPairs"), class = "data.frame", row.names = c(NA, -2L))
Run Code Online (Sandbox Code Playgroud)