6

I have a data frame which contains both numeric and non-numeric columns, say

df <- data.frame(v1=1:20,v2=1:20,v3=1:20,v4=letters[1:20],v5=letters[1:20])

To select only the non-numeric columns I would use

fixCol <- !sapply(df,is.numeric)

But now I also want to include a specific numeric column, say v2. My data frame is very big and the order of the columns changes, so I cannot index it using a number, I really want to use the name 'v2'. I tried

fixCol$v2 = TRUE

but that gives me the warning In fixCol$FR = TRUE : Coercing LHS to a list which makes it impossible to subset my original data frame to get only fixCol

df[,fixCol]

gives: Error in .subset(x, j) : invalid subscript type 'list'

In the end my goal is to scale all numeric columns of my data frame except this one specified column, using something like this

scaleCol = !fixCol
df_scaled = cbind(df[,fixCol], sapply(df[,scaleCol],scale))

How can I best do this?

2 Answers 2

3

We can use a OR condition (|) to get a logical index and then subset the columns of 'df'.

df1 <- df[!sapply(df, is.numeric)|names(df)=='v2']
head(df1,2)
#  v2 v4 v5
#1  1  a  a
#2  2  b  b
Sign up to request clarification or add additional context in comments.

2 Comments

this works great, thanks! How do I make df2 which contains all columns NOT put in df1, without reversing the whole sapply statement? I tried df2 <- df[,!names(df1)] or df2 <- df[,-c(names(df1))] but both give an error. I need df2 as well in order to be able to scale df2 and put it in a new dataframe together with df1.
@Ciska We can either use setdiff or %in% i.e. df2 <- df[setdiff(names(df), names(df1))]
2
fixCol <- !sapply(df,is.numeric)
fixCol <- df[, fixCol]
fixCol$v2 <- df[colnames(df)=="v2"]
head(fixCol)
 # v4 v5 v2
#1  a  a  1
#2  b  b  2
#3  c  c  3
#4  d  d  4
#5  e  e  5
#6  f  f  6

1 Comment

thanks, this works! The answer from akrun uses a little less lines but I am happy with both. Thanks again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.