Leon
Leon

Reputation: 381

Edit every row in data.frame

I'm struggling with editing a dataframe. So my dataset looks like this:

df <- data.frame( Att1 = c("Text Text", "Text2 Text2", "Text3 Text3"), Value = c(1,2,3))

enter image description here

But after every word in every row something(e.g. "∖n") should be added. For example like this:

enter image description here

Does anyone know how to do something like that? Very help would be great! regards

Upvotes: 0

Views: 258

Answers (2)

akrun
akrun

Reputation: 887048

We can do this in a couple of ways. If the space is single, then chartr can replace the space with \n

df$Att1 <- chartr(" ", "\n", df$Att1)

Or with gsub, we replace one or more spaces (\\s+) with \n

df$Att1 <- gsub("\\s+", "\n", df$Att1)

If we have - or \, then replace \\s+ with

df$Att <- gsub("[ \-]+", "\n", df$Att1)

Upvotes: 2

mw0000
mw0000

Reputation: 59

when using sapply one can see very clear what arguments are passed to gsub; | can be used to make alternations in regex

df <- data.frame( Att1 = c("Text Text", "Text2/Text2", "Text3-Text3"), Value = c(1,2,3))

df$Att1 <- sapply(df$Att1, gsub, pattern = "\\s+|\\-|\\/", replacement = "\n")

df$Att1
[1] "Text\nText"   "Text2\nText2" "Text3\nText3"

Upvotes: 1

Related Questions