4

I want to add 1 to all second elements but I am running into a "level" problem I believe here is my code:

list2 = {{{5, 1}}, {{2, 1}, {3, 1}}, {{7, 1}}, {{2, 3}}}

r1pow = Map[(# + {{0, 1}}) &, list2]

the result I got is:

{{{5, 2}}, {{0, 1}} + {{2, 1}, {3, 1}}, {{7, 2}}, {{2, 4}}}

my desired result is:

{{{5, 2}}, {{2, 2}, {3, 2}}, {{7, 2}}, {{2, 4}}}

as you can see it is giving a problem for my second element {{2, 1}, {3, 1}}, how can i fix this problem?

user64494
  • 26,149
  • 4
  • 27
  • 56
Crisp
  • 341
  • 2
  • 7

5 Answers5

8

One way:

list2 = {{{5, 1}}, {{2, 1}, {3, 1}}, {{7, 1}}, {{2, 3}}};
list2 /. {a_Integer, b_Integer} :> {a, b + 1}

(* {{{5, 2}}, {{2, 2}, {3, 2}}, {{7, 2}}, {{2, 4}}} *)
Michael E2
  • 235,386
  • 17
  • 334
  • 747
7

I closed this question a few minutes ago, but I just reopened it because I see that you are specifically asking about fixing your code rather than how to perform a certain operation. You can use this:

Map[# + {0, 1} &, list2, {2}]
{{{5, 2}}, {{2, 2}, {3, 2}}, {{7, 2}}, {{2, 4}}}
  • I removed the extraneous set of brackets
  • I added a levelspec of {2}

In recent versions you should also be able to use MapAt which would be somewhat cleaner:

MapAt[# + 1 &, list2, {All, All, 2}]

Usually faster however is to use the methods you have already been shown by Kuba and now rasher, and discussed further in Elegant operations on matrix rows and columns. I still suspect that this question would not have been asked if you properly understood that method.

Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
3

Showing some of the newer functions

list = {{{5, 1}}, {{2, 1}, {3, 1}}, {{7, 1}}, {{2, 3}}};

1.

ReplaceAt (new in 13.1)

ReplaceAt[list, x : {a_, b_} :> {a, b + 1}, {All, All}]

{{{5, 2}}, {{2, 2}, {3, 2}}, {{7, 2}}, {{2, 4}}}

2.

Threaded (new in 13.1)

# + Threaded[{0, 1}] & /@ list

{{{5, 2}}, {{2, 2}, {3, 2}}, {{7, 2}}, {{2, 4}}}

3.

ApplyTo (new in 12.2)

If we want to change the original list inline:

list //= MapAt[# + {0, 1} &, {;; , ;;}];

list

{{{5, 2}}, {{2, 2}, {3, 2}}, {{7, 2}}, {{2, 4}}}

eldo
  • 67,911
  • 5
  • 60
  • 168
3

Supporting @eldo in an effort of good house maintenance as much as I can.

We can use Query

Query[All, {1 -> ( # + {0, 1} &)}]@list

{{{5, 2}}, {{2, 2}, {3, 2}}, {{7, 2}}, {{2, 4}}}

bmf
  • 15,157
  • 2
  • 26
  • 63
2

Using Cases and Map:

list2 = {{{5, 1}}, {{2, 1}, {3, 1}}, {{7, 1}}, {{2, 3}}};

Cases[list2, x_ :> First@Map[{#[[1]], #[[2]] + 1} &, {x}, {2}]]

({{{5, 2}}, {{2, 2}, {3, 2}}, {{7, 2}}, {{2, 4}}})

E. Chan-López
  • 23,117
  • 3
  • 21
  • 44