Identifying observations specified to a decimal point

Hi all,

I would like to be able to flag measurements that are not rounded to the decimal point- copying the dataframe below here.

data.frame(
weight = c(62.2, 18, 23, 58, 47),
height = c(174.9, NA, 109, 166, 152)
)

In the above example, I'd like to flag the weight observations of 18, 23, 58, and 47- not 62.2, because it includes a significant figure to the tenth.

For height, I'd like to flag height measurements 109, 166, and 152.

Thanks!

For a vector, we can do this as follows

height = c(174.9, NA, 109, 166, 152)
height[height==as.integer(height) & !is.na(height)]
#> [1] 109 166 152

Gotcha- to create a new variable, would it be-

df$roundedheight <- ifelse(df$height==as.integer(df$height) & !is.na(df$height), "yes","no")

Yes, for each variable (height, weight), you can have this information as you did.

with dplyr it would be

df1 <- data.frame(
  weight = c(62.2, 18, 23, 58, 47),
  height = c(174.9, NA, 109, 166, 152)
)

library(dplyr)
check <- function(x){
  x==as.integer(x) & !is.na(x)
}
mutate(df1,
       across(.fns = list(check=check)))
 weight height weight_check height_check
1   62.2  174.9        FALSE        FALSE
2   18.0     NA         TRUE        FALSE
3   23.0  109.0         TRUE         TRUE
4   58.0  166.0         TRUE         TRUE
5   47.0  152.0         TRUE         TRUE
1 Like

This produces a list but I would like to create a new variable- how would I do this in dplyr?

It doesn't create a list. In this example it created weight_check and height_check

The variables don't appear in my data frame.

In my example I hadn't assigned the result to any object. But you could assign it using the <- operator in the normal way

df1 <- function(x){
x==as.integer(x) & !is.na(x)
}

^ like this, in your example?

No the code you highlighted performs only a test and doest feature the assignment operator.
Like this

df1 <- data.frame(
  weight = c(62.2, 18, 23, 58, 47),
  height = c(174.9, NA, 109, 166, 152)
)

library(dplyr)
check <- function(x){
  x==as.integer(x) & !is.na(x)
}

df2 <- mutate(df1,
       across(.fns = list(check=check)))

df2

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.