'R: is there a pandas function map in R?

I want to map values from a named list in R to a dataframe. Is there a equivalent of pandas map function in R?

list = (a=1, b=2)
df = data.frame(a)

df.map(list) in r?

I want to map values of list onto df.

r


Solution 1:[1]

If you are referring to map in pandas, it can be applied to a Pd series like this:

import pandas as pd 
x = pd.Series(['a','b','c'])
LIST = {'a':1,'b':2}
x.map(LIST)

x = pd.Series(['a','b','c'])
0    1.0
1    2.0
2    NaN

In R, you do:

df = data.frame(x = c("a","b","c"))
LIST = list(a=1,b=2)
as.character(LIST[match(df$x,names(LIST))])
"1"    "2"    "NULL"

or using dplyr from github:

dplyr:::recode(df$x,!!!LIST)
[1]  1  2 NA

Solution 2:[2]

I think the way to do this which most closely resembles python's map function is the function recode from the dplyr library:

library(dplyr)

df = data.frame(numbers = c(1,2,3,1,1))

df <- df %>% mutate(tones=recode(numbers, 
                         '1'="do",
                         '2'="re",
                         '3'="mi"))
df

This will get you the following result:

  numbers tones
1       1    do
2       2    re
3       3    mi
4       1    do
5       1    do

Solution 3:[3]

I think you want apply in R.

I'm trying to guess what you want here, assuming you're an R programmer who is more familiar with Python. Here's my guess:

l <- data.frame(a=c(1,2),b=c(3,4))
lgt <- apply(l, 2, function(x) {x > 2})

Here, lgt will print out the following:

   [,1]  [,2]
a FALSE FALSE
b TRUE   TRUE

More importantly, what is going on here? Well, apply takes as an argument a thing, in this case a data frame, a number where 1 is "do this along rows" and 2 is "do this along columns" (this only matters if you're doing some reduction operation such as sum). Its third argument is a function, which we created in-place right there.

If you're stuck, an important tip is to be able to do ?apply in the R prompt to get documentation for a function.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 StupidWolf
Solution 2 future_plant
Solution 3 sdpoll