Jennifer
Jennifer

Reputation: 69

function is introducing NaN's in R

I am working with dataframe ds and this code:

ds[,-1] = apply(ds[,-1],2,function(x){x/sum((x))})

This function should just be running through each cell in each column. Each cell is then divided by the sum of the column. However, after running this function, some columns are populated with NaNs and I am not sure why. How do I go about figuring out why there are NaNs? Is there a way to change my function so I do not get NaNs?

df looks something like this.

sample a b  c
x    2 1  2
x1   3 0 45

Running str:

> str(df)

'data.frame': 99322 obs. of 257 variables: $ sample : int 100021 1000032 100013 10001134 100014568 100014566 104600161 100017 1000188 10002 ... $ FT579627: num 0 0 0 0 0 0 0 0 0 0 ... $ FT579617: num 0 0 0 0 0 0 0 0 0 0 ... $ FT579618: num 0 0 0 0 0 0 0 0 0 0 ... $ FT578292: num 0 0 0 0 0 0 0 0 0 0 ... $ FT578294: num 0 0 0 0 0 0 0 0 0 0 ... $ FT578295: num 0 0 0 0 0 0 0 0 0 0 ... $ FT578296: num NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... $ FT578297: num 0 0 0 0 0 0 0 0 0 0 ... $ FT578321: num 0 0 0 0 0 0 0 0 0 0 ... $ FT578322: num 0 0 0 0 0 0 0 0 0 0 ... $ FT578323: num 0 0 0 0 0 0 0 0 0 0 ... $ FT578324: num 0 0 0 0 0 0 0 0 0 0 ... $ FT578325: num 0 0 0 0 0 0 0 0 0 0 ... $ FT578326: num 0 0 0 0 0 0 0 0 0 0 ... $ FT578327: num 0 0 0 0 0 0 0 0 0 0 ... $ FT578329: num 0 0 0 0 0 0 0 0 0 0 ... $ FT578330: num 0 0 0 0 0 0 0 0 0 0 ... $ FT578405: num 0 0 0 0 0 0 0 0 0 0 ... [list output truncated]

Upvotes: 0

Views: 117

Answers (1)

IRTFM
IRTFM

Reputation: 263481

Perhaps removing the NA's?

ds[,-1] = apply(ds[,-1],2,function(x){x/sum((x, na.rm=TRUE))})

Upvotes: 1

Related Questions