rmahesh
rmahesh

Reputation: 749

Dataframe not populating when I am doing subset?

I have a dataframe that has two columns. One column is the product type, and the other is characters. I essentially want to break that column 'product' into 12 different data frames for each level. So for the first level, I am running this code:

df = df %>% select('product','comments') 
df['product'] = as.character(df['product']) 
df['comments'] = as.character(df['comments'])

Now that the dataframe is in the structure I want it, I want to take a variety of subsets, and here is my first subset code:

df_boatstone = df[df$product == 'water',]
#df_boatstone <- subset(df, product == "boatstone", select = c('product','comments'))

I have tried both methods, and the dataframe is being created, but has nothing in it. Can anyone catch my mistake?

Upvotes: 0

Views: 27

Answers (1)

akrun
akrun

Reputation: 886938

The as.character works on a vector, while df['product'] or df['comments'] are both data.frame with a single column

df[['product']] <- as.character(df[['product']])

Or better would be

library(tidyverse)
df %>% 
    select(product, comments) %>%
    mutate_all(as.character) %>%
    filter(product == 'water')

Upvotes: 2

Related Questions