英文:
How to separate a imported vector into colums in R?
问题
我有一个只包含数字的文本文件,位于单独的一列。
我需要将它们分开,并分配给我有的8个名字之一,每个名字对应一定范围的数字。
例如,我有数字1,2,3,4,5,6,7,8,9,10,我知道1:5是伦敦,6:10是纽约,例如。
我该如何创建两列,其中一列包含如下内容:伦敦 - 1...伦敦 - 5,纽约 - 6...纽约 - 10。非常抱歉如果这显而易见,我是R的新手。
英文:
I have a text file that only contains numbers in a single column.
I need to separate them and assign to one of 8 names I have with the range of numbers for each name.
For example I have numbers 1,2,3,4,5,6,7,8,9,10 and
I know that 1:5 is London and 6:1 is New York for example.
How do I create two columns one containing that will be London - 1... London -5, New York - 6...New York - 10. Very sorry if this is obvious I am new to R.
答案1
得分: 1
你可以创建一个查找表并将数字与之连接。
set.seed(433) # 为了可重复性
创建一个包含城市和关联数字的数据框
dt <- dat <- data.frame(city = c(rep('纽约', 5), rep('伦敦', 5)), number = 1:10)
示例数据,数字1-10的向量
your_data_vector <- as.vector(sample(1:10, 10, replace = TRUE))
将你的数据转换为数据框
your_data_df <- as.data.frame(your_data_vector)
然后与你的数据进行左连接
dplyr::left_join(your_data_df, dt, by = c('your_data_vector' = 'number'))
应该给出以下结果:
your_data_vector city
1 6 伦敦
2 4 纽约
3 1 纽约
4 2 纽约
5 6 伦敦
6 7 伦敦
7 8 伦敦
8 1 纽约
9 10 伦敦
10 9 伦敦
英文:
You can make a look-up table and join the numbers to it.
set.seed(433) # For reproducibility
# Make a dataframe with city in one col, associated #'s in other
dt <- dat <- data.frame(city = c(rep('new york', 5), rep('london', 5)), number = 1:10)
#example data of #'s 1-10 as a vector
your_data_vector <- as.vector(sample(1:10, 10, replace = T))
#change your data to a dataframe
your_data_df <- as.data.frame(your_data_vector)
#then left-join with your data
dplyr::left_join(your_data_df, dt, by = c('your_data_vector' = 'number'))
Should give you:
your_data_vector city
1 6 london
2 4 new york
3 1 new york
4 2 new york
5 6 london
6 7 london
7 8 london
8 1 new york
9 10 london
10 9 london
答案2
得分: 1
require("readr")
x3_01_2020 <- read_csv("~/x3_01_2020.txt", col_names = FALSE)
x3_01_2020$city <- c(rep("London", 5), rep("New York", 5))
英文:
require("readr")
x3_01_2020 <- read_csv("~/x3_01_2020.txt", col_names = FALSE)
x3_01_2020$city <- c(rep("London", 5), rep("New York", 5))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论