我有一个数据框 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/