如何在R中创建新的字符变量?

时间:2019-10-19 04:21:37

标签: r variables character

在我的数据科学课上,我有一个分配的问题:“使用基R函数在数据框birth_data中创建一个名为region的变量,该变量采用值Northeast,Midwest,South和West。”

当前我的代码是

Northeast <- birth_data$state %in% c("CT", "ME", "MA", "NH", "RI", "VT", "NJ", "NY","PA")

Midwest <- birth_data$state %in% c("IL", "IN", "MI", "OH", "WI",
"IA", "KS", "MN", "MO", "NE", "ND", "SD")

South <- birth_data$state %in% c("DE", "DC", "FL", "GA", "MA", "NC", "SC", "VA", "WV", "AL", "KY", "MS", "TN", "AS", "LA", "OK", "TX")

West <- birth_data$state %in% c("AZ", "CO", "ID", "MO", "NV", "NM", "UT", "WY","AK", "CA", "HI", "OR", "WA")

birth_data$region <- c("Northeast","Midwest","South","West")
birth_data <- birth_data$region
  

$<-.data.frame*tmp*中的错误,区域,值= c(“ Northeast”,“ Midwest”,:替换有4行,数据有1103629

我不确定如何解决此问题,但我知道它与向量长度有关。另外,我不确定如何为字符分配变量。如果dplyr被允许,我会感到更加成功。

2 个答案:

答案 0 :(得分:0)

您必须进行更复杂的处理。

git fetch upstream
git switch master
git reset --hard upstream/master

答案 1 :(得分:0)

最简单的是,您可以执行以下操作:

birth_data[Northeast, "region"] <- "Northeast"
birth_data[Midwest, "region"] <- "Midwest"
birth_data[South, "region"] <- "South"
birth_data[West, "region"] <- "West"

您可以得到比这更好的方法,例如构造向量,然后将其添加到data.frame中,但这可以很快完成工作。