开发者

R: Remove character observations in a variable

I have a a variable in a dataframe whose observations are a mix of numeric and character values (due to faulty data entry). How can I subset开发者_开发技巧 in only the observations which are numeric? Suppose the values of filename$varname are (1, 2, 1, 5, 3, a, 3, d, 1), I would like subset out "a" and "d" and keep only the rest of the values which are numeric.


You can make use of the fact that as.numeric will convert character strings to NA whilst keeping numeric data:

x <- c(1, 2, 1, 5, 3, "a", 3, "d", 1)
as.numeric(x)

[1]  1  2  1  5  3 NA  3 NA  1
Warning message:
NAs introduced by coercion 

Now use is.na to test for NA values and exclude these using vector subsetting:

y <- as.numeric(x)
y[!is.na(y)]
[1] 1 2 1 5 3 3 1


Without a reproducible example it is hard to see what your data actually looks like. For instance, is the column of your data frame a factor or just strings? If it is just strings then Andrie's answer works (just use as.numeric()), and if the data is a factor you first need to convert that to strings with as.character(x):

as.numeric(as.character(filename$varname))

You will get some NAs but that is absolutely fine as those values are indeed missing.

EDIT: To clarify abit more. You have a data frame, so you don't want to take values out of the data frame as then it wouldn't be a dataframe anymore (equal rows). You want to correctly assign NA for missing values instead as most statistical functions in R can handle them.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜