[英]Iterating through values in R
我是R的新手,在遍歷值時遇到一些麻煩。
對於上下文:隨着時間的推移,我有60個人的數據,每個人的文件夾中都有自己的數據集(我收到的ID為#s 00:59的數據)。 對於每個人,我需要2個值-給出的響應時間和圖片響應(數字1-16)。 我需要將每個人的數據從寬格式轉換為長格式,然后最終將所有數據集附加在一起。
我的問題是我在編寫一個將為每個人(即每個數據集)執行此操作的循環時遇到麻煩。 這是我到目前為止的代碼:
pam[x] <- fromJSON(file = "PAM_u[x].json")
pam[x]df <- as.data.frame(pam[x])
#Creating long dataframe for times
pam[x]_long_times <- gather(
select(pam[x]df, starts_with("resp")),
key = "time",
value = "resp_times"
)
#Creating long dataframe for pic_nums (affect response)
pam[x]_long_pics <- gather(
select(pam[x]df, starts_with("pic")),
key = "picture",
value = "pic_num"
)
#Combining the two long dataframes so that I have one df per person
pam[x]_long_fin <- bind_cols(pam[x]_long_times, pam[x]_long_pics) %>%
select(resp_times, pic_num) %>%
add_column(id = [x], .before = 1)
如果將上述代碼中的[x]替換為一個人的ID#(例如00),該代碼將運行並為我提供該人想要的數據框。 關於如何執行此操作的任何建議,以便我可以完成全部60個人的工作?
謝謝!
編輯因此,使用library(jsonlite)
而不是library(rjson)
以我需要的格式設置文件,而無需執行所有操作。 感謝所有人的答復,但是解決方案顯然比我想象的要容易得多。
我不知道您的json文件的結構。 如果您不在json文件之類的同一個文件夾中,請嘗試以下操作:
library(jsonlite)
# setup - read files
json_folder <- "U:/test/" #adjust you folder here
files <- list.files(path = paste0(json_folder), pattern = "\\.json$")
# import data
pam <- NULL
pam_df <- NULL
for (i in seq_along(files)) {
pam[[i]] <- fromJSON(file = files[i])
pam_df[[i]] <- as.data.frame(pam[[i]])
}
在這里,您通常會讀取該文件夾中的所有json文件,並構建一個長度為60的向量。然后,沿着該向量排序並讀取所有文件。 我假設最后可以執行bind_rows
或在for循環中添加代碼。 但是請記住在循環開始之前將數據幀設置為NULL
,例如pam_long_pics <- NULL
希望有幫助嗎? 讓我知道。
遵循以下思路可以起作用:
#library("tidyverse")
#library("jsonlite")
file_list <- list.files(pattern = "*.json", full.names = TRUE)
Data_raw <- tibble(File_name = file_list) %>%
mutate(File_contents = map(File_name, fromJSON)) %>% # This should result in a nested tibble
mutate(File_contents = map(File_contents, as_tibble))
Data_raw %>%
mutate(Long_times = map(File_contents, ~ gather(key = "time", value = "resp_times", starts_with("resp"))),
Long_pics = map(File_contents, ~ gather(key = "picture", value = "pic_num", starts_with("pic")))) %>%
unnest(Long_times, Long_pics) %>%
select(File_name, resp_times, pic_num)
編輯 :在讀取JSON文件后,您可能需要也可能不需要包含as_tibble()
,具體取決於您的數據外觀。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.