r - 使用 strsplit 添加新列

标签 r

我有一个数据框 df,它看起来像:

                               V1              V2      V3
1 - SIERRA MIJAS  (MA) - (001M02)  03/12/15 10:00  11,390
1 - SIERRA MIJAS  (MA) - (001M02)  03/12/15 11:00  11,830
1 - SIERRA MIJAS  (MA) - (001M02)  03/12/15 12:00  12,370
2 - SIERRA MIJAS2 (MA)2- (001M02)  03/12/15 13:00  14,550
2 - SIERRA MIJAS2 (MA)2- (001M02)  03/12/15 14:00  15,510
3 - SIERRA MIJAS3 (MA)3- (001M02)  03/12/15 15:00  15,220

我需要在第一列的第一个标记的基础上添加一个新列。 我的意思是,我需要这样的东西:

                               V1              V2      V3 New
1 - SIERRA MIJAS  (MA) - (001M02)  03/12/15 10:00  11,390 1
1 - SIERRA MIJAS  (MA) - (001M02)  03/12/15 11:00  11,830 1
1 - SIERRA MIJAS  (MA) - (001M02)  03/12/15 12:00  12,370 1
2 - SIERRA MIJAS  (MA)2- (001M02)  03/12/15 13:00  14,550 2
2 - SIERRA MIJAS  (MA)2- (001M02)  03/12/15 14:00  15,510 2
3 - SIERRA MIJAS  (MA)3- (001M02)  03/12/15 15:00  15,220 3

我尝试过类似的事情:

df$New<-strsplit(df[,1]," ")[[1]][1]

但是我对任何行都得到相同的值:“1”。

有什么简单的方法可以弄清楚吗?

谢谢

最佳答案

使用 strsplit 实现此目的的一种方法:

#strsplit returns a list so you need a function like sapply to 
#extract the first element from each vector of each element of the list
df$New <- sapply(strsplit(df[,1], ' '), '[', 1)

输出:

> df
                                 V1             V2     V3 New
1 1 - SIERRA MIJAS  (MA) - (001M02) 03/12/15 10:00 11,390   1
2 1 - SIERRA MIJAS  (MA) - (001M02) 03/12/15 11:00 11,830   1
3 1 - SIERRA MIJAS  (MA) - (001M02) 03/12/15 12:00 12,370   1
4 2 - SIERRA MIJAS2 (MA)2- (001M02) 03/12/15 13:00 14,550   2
5 2 - SIERRA MIJAS2 (MA)2- (001M02) 03/12/15 14:00 15,510   2
6 3 - SIERRA MIJAS3 (MA)3- (001M02) 03/12/15 15:00 15,220   3

数据:

df<-read.table(header=T, text='                             V1              V2      V3
"1 - SIERRA MIJAS  (MA) - (001M02)"  "03/12/15 10:00"  11,390
           "1 - SIERRA MIJAS  (MA) - (001M02)"  "03/12/15 11:00"  11,830
           "1 - SIERRA MIJAS  (MA) - (001M02)"  "03/12/15 12:00"  12,370
           "2 - SIERRA MIJAS2 (MA)2- (001M02)"  "03/12/15 13:00"  14,550
           "2 - SIERRA MIJAS2 (MA)2- (001M02)"  "03/12/15 14:00"  15,510
           "3 - SIERRA MIJAS3 (MA)3- (001M02)"  "03/12/15 15:00"  15,220')

关于r - 使用 strsplit 添加新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34078385/

相关文章:

r - readTypedObject(con, type) : Unsupported type for deserialization 中的 SparkR 错误

r - 如何直接在 purrr::accumulate2() 中编写自定义函数

r - 使用subset()时确定哪个列名导致 'undefined columns selected'错误

删除 R 中包含一定比例大写字母的行

r - Sparklyr - 更改 Spark 数据框中的列名称

r - 如何合并动物园对象但使用滞后和变化的列?

r - 您可以在现有轴下添加标签吗?

r - 无法使用 R 从 excel 中导入全部数据

r - 计算r中shapefile中变量的表面积

r - HTTPS 凭证 : obfuscate console or pop-up window input