【问题标题】:Iterating through values in R遍历 R 中的值
【发布时间】:2018-03-08 15:01:07
【问题描述】:

我是 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) 以我需要的格式设置文件,而无需进行所有操作。感谢大家的回复,但解决方案显然比我想象的要容易得多。

【问题讨论】:

  • 您能否提供其中一个人的数据样本?使用purrr 似乎应该很容易,但我不知道数据到底是什么样的。

标签: r iteration


【解决方案1】:

我不知道你的 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 &lt;- NULL

希望有帮助吗?告诉我。

【讨论】:

    【解决方案2】:

    按照这些思路可能会起作用:

    #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(),具体取决于您的数据的外观。

    【讨论】:

    • 谢谢!第一部分似乎有效,但在运行最后一个代码块“mutate_impl(.data,dots)中的错误:评估错误:未设置变量上下文”后,我收到以下错误消息。这似乎没有解除文件的嵌套
    • 看起来我错过了函数的 mutate() 部分中的一些括号。我相应地编辑了我的原始答案。希望它现在有效!
    猜你喜欢
    • 2012-12-28
    • 2018-10-29
    • 2022-08-03
    • 2018-11-07
    • 1970-01-01
    • 2021-09-05
    • 2021-11-19
    • 2010-12-09
    相关资源
    最近更新 更多