Convert a row to a data frame, including column names

I have a string whose structure and length can vary, i.e.

Input:

X <- ("A=12&B=15&C=15")
Y <- ("A=12&B=15&C=15&D=32&E=53")

What I was looking for this line to convert to data frame

Expected Result:

Dataframe x

 A  B  C
 12 15 15

and Dataframe Y

 A  B  C  D  E
 12 15 15 32 53

I'm tired of this:

X <- as.data.frame(strsplit(X, split="&"))

But this did not work for me, as he created only one column and the column name was corrupted.

PS: I can’t hardcode the column names because they can change, and at any point in time a row will contain only one row

+4
source share
2 answers

- read.table. [^0-9]+ , , gsub, , read.table, col.names , , ( gsub)

f1 <- function(str1){
read.table(text=gsub("[^0-9]+", " ", str1), 
         col.names = scan(text=trimws(gsub("[^A-Z]+", " ", str1)), 
             what = "", sep=" ", quiet=TRUE))
 }

f1(X)
#   A  B  C
#1 12 15 15
f1(Y)
#   A  B  C  D  E
#1 12 15 15 32 53
+5

:

library(stringr)
res <- str_match_all(X, "([A-Z]+)=([0-9]+)")[[1]]
df <- as.data.frame(matrix(as.integer(res[,3]), nrow=1))
names(df) <- res[,2]

df
   A  B  C
1 12 15 15
+3

Source: https://habr.com/ru/post/1660255/


All Articles