简体   繁体   中英

Recalculate a column in data.frame

Coming from Python + Pandas, I tried to convert a column in an R data.frame.

In Python/Pandas I'd do it like so: df[['weight']] = df[['weight']] / 1000

In RI came up with this:

convertWeight <- function(w) {
    return(w/1000)
}
df$weight <- lapply(df$weight, convertWeight)

I know of the library dplyr which has the function mutate . That would allow me to transform columns as well.

Is there a different way to mutate a column without using the dplyr library? Something that comes close to Pandas way of doing it?


EDIT

Inspecting the values in df$weight I see this:

> df[1,]
          date   weight
1 1.552954e+12 84500.01

> typeof(df[1,1])
[1] "list"
> df$weight[1]
[[1]]
[1] 84500.01

> typeof(df$weight[1])
[1] "list"

This is neither a number, nor a char. Why list?

Btw: I have the data from a json import like so:

library(rjson)
data <- fromJSON(file = "~/Desktop/weight.json")

# convert json data to data.frame
df <- as.data.frame(do.call("rbind", json_data))
# select only two columns
df <- df[c("date", "weight")]
# now I converted the `date` value from posix to date
# and the weight value from milli grams to kg
# ...

Obviously I have a lot to learn about R.

df$weight = as.numeric(df$weight)
df$weight = df$weight / 1000
# If you would like to eliminate the display of scientific notation:
options(scipen = 999)

# If having difficulty still because of the list, try
df = as.data.frame(df)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM