always.learning
always.learning

Reputation: 169

Create a text list using characters/values from a column in R

library(ggplot2)
library(tidyverse)

mtcars <- rownames_to_column(mtcars, var = "type")

> head(mtcars, 5)
               type  mpg cyl disp  hp drat    wt  qsec vs am gear carb
1         Mazda RX4 21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
2     Mazda RX4 Wag 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
3        Datsun 710 22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
4    Hornet 4 Drive 21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
5 Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2

I am working with a large data set and need to create a text list based on information from a column.

In the example with metcars, how to convert the first column (type) to a text string separated by "|", such as follows:

"Mazda RX4|Mazda RX4 Wag|Datsun 710|Hornet 4 Drive|Hornet Sportabout|etc..."

Saving this list as .txt would be great, given that I will use this text list in another R syntax with grepl.

Thanks for the help!

Upvotes: 0

Views: 209

Answers (1)

karampas
karampas

Reputation: 46

To add the row names of a dataframe as a new column, concatenate them into a text list separated by "|" symbols, and save the resulting text list to a file in R, you can follow these simple steps:

  1. Create a new column named "type" containing the row names.
    mtcars<-rownames_to_column(mtcars, var = "type")

  2. Next extract the values from the "type" column, and create a text list by concatenating them with "|" as the separator:
    type.list <- paste(mtcars$type, collapse = "|")

  3. Finally save the text list to a .txt file. writeLines(type.list, "type.txt")

Upvotes: 1

Related Questions