【问题标题】:How to store loop table data如何存储循环表数据
【发布时间】:2018-08-07 02:15:43
【问题描述】:

我是 R 的新手。有人可以帮我解决这个问题吗?我想存储循环表数据并将其导出到excel文件中,但我没有成功。谢谢。

Qquest7 <- c("A", "B", "A", "A", "A", "B", "B", "B", "B", "A")
Qquest24 <- c("neutral", "somewhat satisfied", "somewhat satisfied", "not able to rate", "somewhat satisfied", "less satisfied", "not able to rate", "dissatisfied", "very satisfied", "dissatisfied")
Qquest25 <- c("not able to rate", "not able to rate", "not able to rate", "somewhat satisfied", "not able to rate", "not able to rate", "dissatisfied", "dissatisfied", "not able to rate", "very satisfied")
Qquest26 <- c("not able to rate", "somewhat satisfied", "not able to rate", "less satisfied", "not able to rate", "neutral", "somewhat satisfied", "neutral", "neutral", "somewhat satisfied")
Qquest27 <- c("very satisfied", "not able to rate", "somewhat satisfied", "neutral", "very satisfied", "neutral", "neutral", "somewhat satisfied", "neutral", "not able to rate")
Qquest28 <- c("not able to rate", "not able to rate", "not able to rate", "not able to rate", "not able to rate", "not able to rate", "very satisfied", "neutral", "somewhat satisfied", "neutral")
Qquest29 <- c("desktop", "laptop", "tablet", "cellphone", "desktop", "desktop", "tablet", "laptop", "cellphone", "laptop")        

df <- data.frame(Qquest7, Qquest24, Qquest25, Qquest26, Qquest27, Qquest28, Qquest29)

library(openxlsx)
trial2429 <- c("Qquest24","Qquest25", "Qquest26", "Qquest27", "Qquest28", "Qquest29")
x <- data.frame()
y <- data.frame()
for (i in df[trial2429]){
  x[i] <- table(df$Qquest7, i)
  y <- print(x)
}
write.xlsx(y, file = "trial2429.xlsx")

【问题讨论】:

  • Export data to Excel的可能重复
  • “未成功”究竟是什么意思?什么是错误/问题?
  • @LukeC:我添加了数据
  • @LukeC:非常感谢。解决了,解决方案比我想象的要复杂。
  • @LukeC:谢谢:D

标签: r for-loop


【解决方案1】:

我不是 100% 你想要的输出,但我用于我自己目的的这个函数可能会为你解决问题。使用您的 dftrial2429 作为数据,首先给 trial2429 一些名称:

names(trial2429) <- trial2429

现在,构建一个函数,该函数接受一个列表并按顺序将其内容添加到 .csv 文件中:

## Export list
export_results <- function(df_list, file_name = "outfile.csv") {
  if (file.exists(file_name)) {
    file.remove(file_name)
    print("Removed old file.")
  }

  ## Clean export function
  writeout <- function(table_name) {
    write(table_name, file_name, sep = ",", append = TRUE)
    tab.out <- df_list[[table_name]]
    tab.out <- cbind(rownames(tab.out), tab.out)
    write.table(
      tab.out,
      file_name,
      row.names = FALSE,
      sep = ",",
      append = TRUE
    )
    write("", file_name, sep = ",", append = TRUE)
  }

  for (i in names(df_list)) {
    writeout(i)
  }
}

获取您所关注的每个问题的表格版本,并将其存储在列表中:

q.list <- lapply(trial2429, function(x){
  table(df$Qquest7, df[[x]])
})

在该列表上调用上面定义的函数:

export_results(q.list, file_name = "trial2429.csv")

它会抛出一些警告消息,但似乎不会导致任何问题 - 您的输出在 Excel 中应该是这样的:

编辑:固定列数问题

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多