[英]R: Applying factor values from one column to another
I am trying to process municipal information in R and it seems that factors (to be exact factor()
). 我正在尝试在R中处理市政信息,并且似乎有一些因素(确切地说是factor()
)。 are the best way to achieve my goal. 是实现我的目标的最好方法。 I am only starting to get the hang of R, so I imagine my problem is possibly very simple. 我才刚开始理解R,所以我想我的问题可能很简单。
I have the following example dataframe to share (a tiny portion of Finnish municipalities): 我有以下示例数据框要共享(芬兰市政当局的一小部分):
municipality<-c("Espoo", "Oulu", "Tampere", "Joensuu", "Seinäjoki",
"Kerava")
region<-c("Uusimaa","Pohjois-Pohjanmaa","Pirkanmaa","Pohjois-Karjala","Etelä-Pohjanmaa","Uusimaa")
myData<-cbind(municipality,region)
myData<-as.data.frame(myData)
By default R converts my character columns into factors, which can be tested with str(myData)
. 默认情况下,R将我的字符列转换为可以用str(myData)
测试的因子。 Now to the part where my beginner to novice level R skills end: I can't seem to find a way to apply factors from column region
to column municipality
. 现在到我的初学者到R级新手技能结束的部分:我似乎找不到一种将要素从列region
到列municipality
。
Let me demonstrate. 让我示范一下。 Instead of having the original result 而不是原始结果
as.numeric(factor(myData$municipality))
[1] 1 4 6 2 5 3 [1] 1 4 6 2 5 3
I would like to get this, the factors from myData$region applied to myData$municipality. 我想得到这个,来自myData $ region的因素适用于myData $ municipality。
as.numeric(factor(myData$municipality))
[1] 5 4 2 3 1 5 [1] 5 4 2 3 1 5
I welcome any help with open arms. 我欢迎张开双臂的帮助。 Thank you. 谢谢。
To better understand the use of factor in R have a look here . 为了更好地理解R中factor的使用,请看这里 。
If you want to add factor levels, you have to do something like this in your dataframe: 如果要添加因子水平,则必须在数据框中执行以下操作:
levels(myData$region)
[1] "Etelä-Pohjanmaa" "Pirkanmaa" "Pohjois-Karjala" "Pohjois-Pohjanmaa" "Uusimaa"
> levels(myData$municipality)
[1] "Espoo" "Joensuu" "Kerava" "Oulu" "Seinäjoki" "Tampere"
> levels(myData$municipality)<-c(levels(myData$municipality),levels(myData$region))
> levels(myData$municipality)
[1] "Espoo" "Joensuu" "Kerava" "Oulu" "Seinäjoki"
[6] "Tampere" "Etelä-Pohjanmaa" "Pirkanmaa" "Pohjois-Karjala" "Pohjois-Pohjanmaa"
[11] "Uusimaa"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.