0

I have the data frame, and one of the column (alpha) has been merged with its space. I want to split that column, and I'm trying to collect the column name from the user before splitting it, however, the code below gives me the output as [,1] [,2]

code:

library(dplyr)
library(tidyr)
library(stringr)
library(tidyverse)
df <- data.frame(ID=11:12, alpha=c('a b', 'b c', 'x y'))
library(stringr)
column_name <- readline(prompt="Enter the desired column name: ")
df1<-str_split_fixed(df$column_name, " ", 2)
df1

What is the best way to accomplish the necessary outcomes in R? Could someone please assist me?

kumaran T
  • 27
  • 2
  • 8
  • 1
    Does this answer your question? [Dynamically select data frame columns using $ and a character value](https://stackoverflow.com/questions/18222286/dynamically-select-data-frame-columns-using-and-a-character-value) – Rory S Jul 29 '21 at 09:54

1 Answers1

1

The problem is that $ is based on columnname. It searches for the column 'column_name' which does not exist.

The code below searches for the string in the variable columnname

library(dplyr)
library(tidyr)
library(stringr)
library(tidyverse)
df <- data.frame(ID=11:13, FOO=c('a b', 'b c', 'x y'))
library(stringr)
column_name <- readline(prompt="Enter the desired column name: ")
df1<-str_split_fixed(df[[column_name]], " ", 2)
df1
Koot6133
  • 1,428
  • 15
  • 26