如何在R中将导入的向量分成列?

huangapple go评论109阅读模式
英文:

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

  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'))

  1. 应该给出以下结果:

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.

  1. set.seed(433) # For reproducibility
  2. # Make a dataframe with city in one col, associated #&#39;s in other
  3. dt &lt;- dat &lt;- data.frame(city = c(rep(&#39;new york&#39;, 5), rep(&#39;london&#39;, 5)), number = 1:10)
  4. #example data of #&#39;s 1-10 as a vector
  5. your_data_vector &lt;- as.vector(sample(1:10, 10, replace = T))
  6. #change your data to a dataframe
  7. your_data_df &lt;- as.data.frame(your_data_vector)
  8. #then left-join with your data
  9. dplyr::left_join(your_data_df, dt, by = c(&#39;your_data_vector&#39; = &#39;number&#39;))

Should give you:

  1. your_data_vector city
  2. 1 6 london
  3. 2 4 new york
  4. 3 1 new york
  5. 4 2 new york
  6. 5 6 london
  7. 6 7 london
  8. 7 8 london
  9. 8 1 new york
  10. 9 10 london
  11. 10 9 london

答案2

得分: 1

  1. require("readr")
  2. x3_01_2020 <- read_csv("~/x3_01_2020.txt", col_names = FALSE)
  3. x3_01_2020$city <- c(rep("London", 5), rep("New York", 5))
英文:
  1. require(&quot;readr&quot;)
  2. x3_01_2020 &lt;- read_csv(&quot;~/x3_01_2020.txt&quot;, col_names = FALSE)
  3. x3_01_2020$city &lt;- c(rep(&quot;London&quot;, 5), rep(&quot;New York&quot;, 5))

huangapple
  • 本文由 发表于 2020年1月3日 19:07:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/59577509.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定