如何依次遍历 r data.frame 中的每一行然后每一列?

How to sequentially go through every row and then every column in an r data.frame?

我有一些调查数据是通过 Google 表格输入的。 Google 生成回复的电子表格,但我需要做的是将这些数据拆分成单独的回复,这样人们就可以阅读它,就好像它是在博客或其他东西上发布的采访一样。

假设我有这样的东西:

1st Question      2nd Question      3rd Question
"Response1 q1"    "Response1 q2"    "Response1 q3"
"Response2 q1"    "Response2 q2"    "Response2 q3"
"Response3 q1"    "Response3 q2"    "Response3 q3"

第一行(第 headers 列)是问题,每一行都填满了对这些问题的回答。我想要制作的是这样的:

1st Question
-------
Response1 q1

2nd Question
-------
Response1 q2

3rd Question
-------
Response1 q3

基本上,对于每个受访者,我想制作 1 个单独的文件,以线性方式显示他们的问题回答。

我已经给了你我试图解决的问题的细节,以防我的特殊情况有捷径,但一般来说,如果你在 R 中有一个 data.frame,无论出于何种原因,您需要遍历 row-by-row,然后 column-by-column,除了编写一些 for 循环之外,如何实现这一点?

这是使用循环执行此操作的标准方法:

 for(i in 1:nrow(df)){ #traverse rows

    for(ii in 1:ncol(df)){ #traverse cols

    #do whatever

    }
}

其中 df 是您的数据框

假设您的数据在数据框中(使用字符串,而不是因子),如下所示:

qdata = structure(list(Q1.text = c("1r.text", "2r.text", "3r.text"), 
    Q2.text = c("1r.text", "2r.text", "3r.text"), Q3.text = c("1r.text", 
    "2r.text", "3r.text"), Q4.text = c("1r.text", "2r.text", 
    "3r.text")), .Names = c("Q1.text", "Q2.text", "Q3.text", 
"Q4.text"), class = "data.frame", row.names = c(NA, -3L))

(下次,与 dput 分享您的数据,使其结构易于重现。)

我会选择矢量化解决方案。在这里,我转换为矩阵,然后将列名粘贴到条目中,用新行 ("\n") 和破折号分隔,如您的示例所示。

qdata.m = as.matrix(qdata)
# Next, we take advantage of "recycling" of the column names,
# pasting them to the matrix values with a newline "\n" separator.
qdata.m = paste(colnames(qdata.m), "-------", t(qdata.m), sep = "\n")
# Note that matrices are normally used column-wise, so I transpose t()
# to make it row-wise instead.

# cat is good for putting text into a file. We'll separate each
# element with two line breaks.
cat(qdata.m, sep = "\n\n")

# Q1.text
# -------
# 1r.text
# 
# Q2.text
# -------
# 1r.text
# 
# Q3.text
# -------
# 1r.text
# etc.

这里使用 cat 的一个优点是它可以直接打印到一个文件(或者你可以先用 sink 打开一个连接---更多细节请参见他们的相关帮助页面).

在更一般的情况下,如果您需要逐行然后逐列,您可以使用嵌套的 for 循环来完成。看起来你当时并没有真正使用数据帧结构,所以你可以用 unlist() 将它变成一个向量事实上,在这种情况下,这可能比我上面做的更容易:

qvect = unlist(qdata)
# pasting much as above, with an order() to sort by the text
# (the order step may take more care with non-dummy text that isn't
#  alphabetical)
qvect = paste(names(qvect), "--------", qvect, sep = "\n")[order(qvect)]

然后就可以cat如上进行