使用 rbind two 组合两个单列变量
using rbind two combine two one-column variables
我试图简单地对两列使用 rbind
并且我使用以下内容(所有变量都是城市名称并且 r 将它们视为因素)
firstcitynames <- rcffull$X1CityName
secondcitynames <- rcffull$X2CityName
allcitynames <- rbind(firstcitynames, secondcitynames)
allcitynames
然后当到达 View(allcitynames)
时,我得到的只是一堆数字而不是名称:
[,2276] [,2277] [,2278] [,2279] [,2280] [,2281]
[,2282] [,2283] [,2284] [,2285] [,2286] [,2287]
有什么建议吗?
您需要使用 as.character(df$var)
将因子转换为字符
这是一个插图
a <- factor(letters[1:10])
b <- factor(LETTERS[1:10])
rbind(a,b)
## [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
## a 1 2 3 4 5 6 7 8 9 10
## b 1 2 3 4 5 6 7 8 9 10
rbind(as.character(a), as.character(b))
## [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
## [1,] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j"
## [2,] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J"
假设 firstcitynames
和 secondcitynames
是类型因子
你可以试试这个
rbind(levels(firstcitynames),levels(secondcitynames))
这个也有效:
firstcitynames <- as.tibble(rcffull$X1CityName)
secondcitynames <- as.tibble(rcffull$X2CityName)
allcitynames <- rbind(firstcitynames, secondcitynames)
allcitynames
我试图简单地对两列使用 rbind
并且我使用以下内容(所有变量都是城市名称并且 r 将它们视为因素)
firstcitynames <- rcffull$X1CityName
secondcitynames <- rcffull$X2CityName
allcitynames <- rbind(firstcitynames, secondcitynames)
allcitynames
然后当到达 View(allcitynames)
时,我得到的只是一堆数字而不是名称:
[,2276] [,2277] [,2278] [,2279] [,2280] [,2281]
[,2282] [,2283] [,2284] [,2285] [,2286] [,2287]
有什么建议吗?
您需要使用 as.character(df$var)
这是一个插图
a <- factor(letters[1:10])
b <- factor(LETTERS[1:10])
rbind(a,b)
## [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
## a 1 2 3 4 5 6 7 8 9 10
## b 1 2 3 4 5 6 7 8 9 10
rbind(as.character(a), as.character(b))
## [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
## [1,] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j"
## [2,] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J"
假设 firstcitynames
和 secondcitynames
是类型因子
你可以试试这个
rbind(levels(firstcitynames),levels(secondcitynames))
这个也有效:
firstcitynames <- as.tibble(rcffull$X1CityName)
secondcitynames <- as.tibble(rcffull$X2CityName)
allcitynames <- rbind(firstcitynames, secondcitynames)
allcitynames