stefan485
stefan485

Reputation: 39

Unexpected change of column name to V1

When running my code I have 2 issues when executing the code after the line "View(df)".

Firstly, I try to delete the first two empty rows, but instead everything gets deleted. EDIT: The selection of the first 2 rows needs to be done with regex. Anything which looks empty should be deleted (An unknown number of spaces or line breaks).

Secondly, the column name is changing unexpectedly to V1. (This is also happening when running the last line of the code without the previous "regex line"). Surprisingly, this issue does not occur when I do not delete the column "a" first.

EDIT: a screen shot after performing the code without the second to last line of code.

column name is changing unexpectedly to V1

Any help is much appreciated!

library(dplyr)

df <- data.frame(a=c(1:8), b=c(" ", " ","tomato", "apple", "orange 1", "peach", "lemon", "orange 2"))
df <- dplyr::select(df, -c(a))
df <- df %>% rename(fruit = b)
View(df)

df <- df[grepl("[[:alnum:]]", df$fruit), ]
df <- df[-1, ]

Upvotes: 1

Views: 242

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388982

If you want to use regex and select rows with any alphabetic characters, we can do

subset(df, grepl('[A-Za-z]', friut))

#     friut
#3   tomato
#4    apple
#5 orange 1
#6    peach
#7    lemon
#8 orange 2

Or similarly,

subset(df, grepl('[:alpha:]', friut))

Looking at the data, selecting non-empty rows also seem to work.

subset(df, friut != ' ')

Upvotes: 1

Related Questions