从R中的数字和字符数据类创建数据帧

时间:2016-02-15 07:00:53

标签: r vector

作为背景。我有两个数字数据值(比如年龄和值)和两个字符数据类(性别和通信)。性别分类为男性和女性,而通讯则分类为短信和字母。

我尝试按如下方式创建数据框:

age <- c(mean(age))

value <- c(mean(value))

gender <- c("male", "female")

comms <- c("sms", "letter")

together <- data.frame(age, value, gender, comms)

它给出了一个参数错误,意味着行数不同。请帮助我们如何为这些数据类创建数据框。

我想创建一个看起来像

的输出
Age     value    gender    comms
24      500       Male      sms
24      500       Female    letter
24      500       Female    sms
24      500       Male      letter

1 个答案:

答案 0 :(得分:0)

好的,你的例子很混乱,不清楚你想做什么。据我了解,您可以创建list data.frames并使用rbindlist

age <- c(24)

value <- c(400)

gender <- rep_len(c("Male","Female"), length(comms1)) #as suggested by @Jimbou

comms <- c("sms", "letter")

comms1 <- c("sms", "letter", "email", "telephone", "morsecode", "whitedove")

df1 <- data.frame(age, value, gender, comms)
df3 <- data.frame(age, value, gender, comms1)
ls <- list(df1, df3)
rbindlist(ls)

#  age value gender     comms
#1:  24   400   male       sms
#2:  24   400 female    letter
#3:  24   400   male       sms
#4:  24   400 female    letter
#5:  24   400   male     email
#6:  24   400 female telephone
#7:  24   400   male morsecode
#8:  24   400 female whitedove