mercredi 30 octobre 2019

R - Split String with conditions

I have a string splitting related problem. I have a huge amount of files, which names are structures like this:

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

I need to extract the Stationnames, e.g. Place1, Nice_Place1 and so on. Its either "Place" and a number or "Nice_Place" and a number.

I tried this to get the stationnames for "Place" and a number and it works geat, but this doesnt give me the correct name in case of "Nice_Place"...because it handles it as 2 words.

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

My idea is now to use if...else. So If the Stationname in the example above is "Nice", add the 3rd part of the stringsplit with an underscore. Unfortunatley I am totally new to this if else condition.

Can somebody please help?

Aucun commentaire:

Enregistrer un commentaire