string - [R - 带条件的拆分字符串

我有大量这样结构的文件:


filenames = c("NO2_Place1_123_456789.dat","NO2_Nice_Place_123_456789.dat","NO2_Nice_Place_123_456789.dat","NO2_Place2_123_456789.dat")



我需要提取Stationnames,例如 Place1,Nice_Place1等,它可以是“ Place ”和一个数字,也可以是“ Nice_Place ”和一个数字。


Station = strsplit(filenames[1],"_")[[1]][2] #Works


Station = strsplit(filenames[2],"_")[[1]][2] #Doesnt work



预期输出:


Station = strsplit(filenames[1],"_")[[1]][2] #Station = Place


Station = strsplit(filenames[2],"_")[[1]][2] #Station = Nice -- not correct I want to have"Nice_Place"



所以当我得到


Station = strsplit(filenames[2],"_")[[1]][2] #Station = Nice



我要添加一个条件,即如果Station为“ Nice ”,则应添加,strsplit(filenames[2],"_")[[1]][3]带下划线!

我现在找到了一种方法:


filenames = c("NO2_Place1_123_456789.dat","NO2_Nice_Place1_123_456789.dat","NO2_Nice_Place2_123_456789.dat","NO2_Place2_123_456789.dat")



Station = strsplit(filenames[2],"_")[[1]][2]



if (Station =="Nice"){



 Station = paste(Station, strsplit(filenames[2],"_")[[1]][3], sep ="_")


}



时间:

我们可以用sub


sub("^[^_]+_(.*Placed*).*","1", filenames[2])


#[1]"Nice_Place1" 



...