我的資料框中有一個字串變數型別,它有一個長字串(它是一個 JSON 回應),其中包含我想要的列的名稱和它后面的值。
我的資料框如下所示:
- 每一行都是參與者
- 參與者欄是每個參與者的串列
- Responses有一個帶有 JSON 回應的字串條目,我希望條目的開頭是變數,而“:”之后的內容是值。
| 參與者 | 回應 |
|---|---|
| 艾米麗 | {"participantAge":"40","participantEducation":"單身漢"} |
| 道格 | {"participantAge":"35","participantEducation":"Bachelors"} |
因此,例如,目標是讓參與者年齡列作為條目的值和參與者教育作為條目的列
| 參與者 | 回應 | 參與者年齡 | 參與者教育 |
|---|---|---|---|
| 艾米麗 | {"} | 40 | 學士 |
| 道格 | {"} | 35 | 學士 |
我以前可以通過將 JSON 回應轉換為字典來使用 python 做到這一點,但我不確定如何在 R 中實作這一點。
uj5u.com熱心網友回復:
dplyr您可以使用和執行以下操作jsonlite
library(dplyr)
library(jsonlite)
df %>%
rowwise() %>%
mutate(Response = list(parse_json(Response))) %>%
unnest_wider(Response)
輸出:
Participant participantAge participantEducation
<chr> <chr> <chr>
1 Emily 35 Bachelors
2 Doug 40 Bachelors
輸入:
df = structure(list(Participant = c("Emily", "Doug"), Response = c("{\"participantAge\":\"35\",\"participantEducation\":\"Bachelors\"}",
"{\"participantAge\":\"40\",\"participantEducation\":\"Bachelors\"}"
)), class = "data.frame", row.names = c(NA, -2L))
uj5u.com熱心網友回復:
你可以試試這個jsonlite包:
library("jsonlite")
dat_df <- data.frame(Emily='{"participantAge":"40","participantEducation":"Bachelors"}',
Doug='{"participantAge":"35","participantEducation":"Bachelors"}')
fromJSON_rec <- apply(dat_df, 2, fromJSON)
new_df <- data.frame(matrix(NA, nrow=2, ncol=3))
colnames(new_df) <- c("Participant", "participantAge", "participantEducation")
for(i in 1:length(fromJSON_rec)){
new_df[i,] <- c(names(fromJSON_rec)[i],
fromJSON_rec[[names(fromJSON_rec)[i]]][["participantAge"]],
fromJSON_rec[[names(fromJSON_rec)[i]]][["participantEducation"]])
}
> dat_df
Emily Doug
1 {"participantAge":"40","participantEducation":"Bachelors"} {"participantAge":"35","participantEducation":"Bachelors"}
> new_df
Participant participantAge participantEducation
1 Emily 40 Bachelors
2 Doug 35 Bachelors
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/475774.html
上一篇:如何在回圈中將條目添加到存盤在List中的每個Map中
下一篇:在所有實體中獲取屬性的字典
