2015-12-03 54 views
1

我有一个数据帧DF,它看起来像:添加新列strsplit

       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

回答

1

方式一:

#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') 
+0

这将是有用的,如果第一个标记八方通有一个字符len GHT。但它没有。在其他行中可以是“1”或“430”。 – Lev

+0

好吧,我用'strsplit'更新了答案,那么这将适用于不同的数字。 – LyzandeR

+0

谢谢。它的工作完美...我有一些警告,因为有一些西班牙字符,如“ó”“ᔓ - ”,R不喜欢,并在这些行中,新列是NA ..但任何方式。我的主要问题解决了。谢谢。 – Lev