如何存储循环表数据

时间:2018-08-06 12:59:27

标签: r for-loop

我是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")

1 个答案:

答案 0 :(得分:0)

我并不是您期望的输出的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中应该是这样的:

enter image description here

编辑:固定的列数问题