子集数据帧行作为列表返回?

时间:2018-03-22 15:30:27

标签: r dataframe vector

我想从数据帧的一行中创建一个字符串向量。没有它的行和列名称。这是我的数据框架。

agreement = c("Strongly Disagree"," Disagree", "Neither", "Agree", "Strongly Agree")
likelihood = c("Very unlikely","Unlikely", "Neither", "Likely", "Very Likely")
df <- as.data.frame(rbind(agreement, likelihood))

获得数据框后,如何在没有列值的情况下返回字符向量? E.g。

> "Strongly Disagree"," Disagree", "Neither", "Agree", "Strongly Agree"

我尝试使用as.character,但我得到的回报是数值。

as.character(df[1,1:5])
> "1" "1" "1" "1" "1"

我也试过了as.vector,但它返回了一个包含列名的列表。

as.vector(df[1,1:5])
>                        V1        V2      V3    V4             V5
agreement Strongly Disagree  Disagree Neither Agree Strongly Agree

任何帮助将不胜感激!

3 个答案:

答案 0 :(得分:3)

创建数据框时,您需要将FALSE设置为df <- as.data.frame(rbind(agreement, likelihood), stringsAsFactors = FALSE)

as.character(df[1,1:5])

"Strongly Disagree" " Disagree" "Neither" "Agree" "Strongly Agree" 现在导致

df[1,]

检索所有行或列时,您只需将该字段留空即可(例如echo -e '12345\t"compilation problem"\tfullScan.java' | { IFS=$'\t' read -r -a FOO echo number: ${FOO[0]} echo string: ${FOO[1]} echo file: ${FOO[2]} } 返回包含所有列的第一行)

答案 1 :(得分:0)

除了@ YusufSyakur对as.character部分的回答之外,您应该知道具有多个列的data.frame的子集始终是data.frame本身。即使只有一排。而data.frame只是一个顶部有额外糖的列表,因此as.vector会删除该糖并离开列表。

答案 2 :(得分:0)

请记住,您可以使用tibbles而不是数据帧(https://cran.r-project.org/web/packages/tibble/vignettes/tibble.html

默认情况下,带有tice stings的

不会转换为因子。所以在你的情况下你可以使用:

[0] => Aaa
[1] => Äää
[2] => Ccc
[3] => Ooo
[4] => Ööö
[5] => Rrr
[6] => Zzz